一个明显的解决方案是设置标签:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
myCB[i].Tag = i;
tableLayoutPanel1.Controls.Add(myCB[i]);
}
然后:
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
Control control = (Control) sender;
label1.Text = sender.Tag.ToString();
}
另一种选择是在事件处理程序中捕获信息,最简单的是使用 lambda 表达式或匿名方法:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index = i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => label1.Text = index.ToString();
tableLayoutPanel1.Controls.Add(myCB[i]);
}
或更复杂的行为:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index= i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => DoSomethingComplicated(index, s, e);
tableLayoutPanel1.Controls.Add(myCB[i]);
}
(您DoSomethingComplicated
适当声明的地方)。