I need to dynamically create buttons (one for loop) and add "onClick" and "doubuleClick" events on it.

I did it like this:

  Button bt = new Button();

  bt.Click += bt_Click;         
  bt.DoubleClick += bt_DoubleClick;

  private void bt_Click(object sender, EventArgs e)
  {
        label1.Text = this.Text;
  }

  private void bt_DoubleClick(object sender, EventArgs e)
  {
        //some code
  }

First: My "bt_Click" method gets "main form" text in "label1". In debugger I see that sender is a button. What is wrong with it?

Second: My "bt_DoubleClick" event do not react at all, am I doing something wrong here?

Any help is appreciated.

有帮助吗?

解决方案 3

The easiest way to do this it is to use "datagrid". Datagread has the great support for all events and for organization of items (image, text and so on). I have made "save" or "open" dialog form to browse content from remote SFTP server, very easy with datagrad, but I had a problem to do it with buttons or labels.

其他提示

You should cast sender to Button to get the bt.Text:

Button bt = new Button();
bt.Click += bt_Click;
bt.Text = "click me";
bt.Location = new Point(100,100);
this.Controls.Add(bt);

private void bt_Click(object sender, EventArgs e)
{
    label1.Text = (sender as Button).Text;
}

Buttons doesn't react to double click event. You can read it here in detail.

In response to the first question, if I understand you correctly, in this.Text, this refers to the form because the method bt_Click is a member of the Main Form class. I think you might have meant to do:

private void bt_Click(object sender, EventArgs e)
  {
        label1.Text = (Button)sender.Text;
  }

Second: Is this just a case of the bt_Click handler firing twice?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top