-1

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

如何做到这一点?

4

2 回答 2

1

您可以使用 EventHandler 的 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);
于 2013-08-08T07:51:51.807 回答
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
   }
于 2013-08-08T07:54:08.987 回答