1

Let's look at the following code in which I'm creating a List of buttons.

List<System.Windows.Forms.Button> buttons = new List<System.Windows.Forms.Button>(); 

for(int i = 0; i < 5; i++) {
    buttons.Add(  System.Windows.Forms.Button>()  );
    buttons[i].Name = "button_" + i.ToString();
    this.Controls.Add(buttons[i]);
    buttons[i].Click += new System.EventHandler(this.Bt_windowClick);
}

The next part is where I'm confused. When this delegate is called I would like it to tell me which button was actually clicked. How would I do this?

void Bt_windowClick(object sender, EventArgs e)
{
    // I would like to get the name of the button that was clicked
}

Thank you in advance for your support!

4

1 回答 1

4

Sender 对象是一个按钮,它引发了事件。因此,只需将其转换为Button类型:

void Bt_windowClick(object sender, EventArgs e)
{
    Button button = (Button)sender;
    // use button
    MessageBox.Show(button.Name);
}
于 2012-11-18T21:38:39.683 回答