1

我正在动态地将一堆控件添加到表单中。每个控件都调用相同的方法,在该方法中,我需要知道执行该操作的控件的数组索引。

CheckBox[] myCB = new CheckBox[100];
int i;
for (i = 0; i < 100; i++)
{
    myCB[i] = new CheckBox();
    myCB[i].Text = "Clicky!";
    myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
    tableLayoutPanel1.Controls.Add(myCB[i]);
}

private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
    label1.Text = sender.???array index property???.ToString();
}

因此,如果我单击myCB[42] label1将显示“42”当然,如果有更简单的方法来处理动态控件,我会很感激指针。

4

4 回答 4

5
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
    label1.Text = Array.IndexOf(myCB, (CheckBox)sender).ToString();
}
于 2009-06-09T17:50:25.730 回答
3

控件应该有一个 Tag 属性。也许您可以将索引附加到标签。虽然你会招致拳击......

于 2009-06-09T17:48:52.880 回答
3
int j = i;
myCB[i].Click += delegate(object sender, EventArgs e) {
 // here you can use "j"

};
于 2009-06-09T17:52:23.543 回答
2

一个明显的解决方案是设置标签:

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适当声明的地方)。

于 2009-06-09T17:50:43.470 回答