我想在现有按钮上添加新的事件句柄。我在表单中创建了9个按钮,希望在单击时显示每个名称,但不想手动显示每个按钮消息。
如何做到这一点?
您可以使用EventHandler的发送方属性来执行此操作。此示例使用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);
您可以编写类似的代码
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
}