如何在现有的按钮c#上放置新的事件句柄?

时间:2013-08-08 07:47:19

标签: c# button delegates event-handling

我想把现有的按钮新事件句柄。我在表单中创建了9个按钮,并且想要在单击时显示每个名称,但不想手动添加每个按钮消息。

如何做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用事件处理程序的sender属性来执行此操作。此示例使用winforms按钮:

SomeButtonClicked(object sender, EventArgs e)
{
     var button = sender as Button;
     MessageBox.Show(button.Name);
}

然后你可以将这个事件添加到多个按钮,即:

button1.Click += new System.EventHandler(SomeButtonClicked);
button2.Click += new System.EventHandler(SomeButtonClicked);
button3.Click += new System.EventHandler(SomeButtonClicked);

答案 1 :(得分:1)

你可以编写类似这样的代码

   private void MainForm_Load(object sender, EventArgs e) {
     ...
     // Assigning on click event, assuming that all your buttons are on the MainForm
     foreach (Control ctrl in Controls) {
        Button btn = ctrl as Button;

        if (!Object.ReferenceEquals(null, btn))
          btn.Click += onButtonClick;
     }
   ...

   // On click itself
   private void onButtonClick(Object sender, EventArgs e) {
     Button btn = sender as Button;

     String name = btn.Name; // <- Or whichever property of the button you want
   }