【发布时间】:2013-11-01 18:20:07
【问题描述】:
我在 C# WFA 中有一个 Button 数组,我想为单击数组中的任何按钮创建一个事件。 我该怎么做? 以及如何知道它在数组中的哪个位置? 我知道发件人就是按钮本身
【问题讨论】:
标签: c# windows winforms button
我在 C# WFA 中有一个 Button 数组,我想为单击数组中的任何按钮创建一个事件。 我该怎么做? 以及如何知道它在数组中的哪个位置? 我知道发件人就是按钮本身
【问题讨论】:
标签: c# windows winforms button
您可以使用for 循环来关闭包含当前索引的变量:
for(int i = 0; i < buttons.Length; i++)
{
//it's important to have this; closing over the loop variable would be bad
int index = i;
buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
【讨论】:
您可以将事件处理程序添加到 for 循环中的每个按钮。
在处理程序内部,您可以调用array.IndexOf((Button)sender)。
【讨论】:
试试这个
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Button[] myButtons = new Button[10];
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i < myButtons.Length; i++)
{
int index = i;
this.myButtons[i] = new Button();
this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
this.myButtons[i].Name = "button" + (index + 1);
this.myButtons[i].Size = new System.Drawing.Size(70, 23);
this.myButtons[i].TabIndex = i;
this.myButtons[i].Text = "button" + (index + 1);
this.myButtons[i].UseVisualStyleBackColor = true;
this.myButtons[i].Visible = true;
myButtons[i].Click += (sender1, ex) => this.Display(index+1);
this.Controls.Add(myButtons[i]);
}
}
public void Display(int i)
{
MessageBox.Show("Button No " + i);
}
}
}
【讨论】:
Display 的语法不正确,您是在 for 循环中调用该方法,而不是从中创建委托。