2

我想知道我应该如何为标签数组中的每个数组元素分配一个 eventHandler。我知道不可能为每个事件处理程序创建一个方法,那么解决方案是什么?谢谢!

for(int i = 0, i < 10; i++)
{
    lbs[i] = new Label();
    lbs[i].Location = new System.Drawing.Point(76 + f, 164);
    lbs[i].Size = new System.Drawing.Size(49, 17);
    //able to perform this, but wont able to create a method for this
    lbs[i].Click += new System.EventHandler(lbs[i]_Click);
}

//can't do this, what is alternative?
public void lbs[i]_Click(object sender, EventArgs e)
{

}
4

1 回答 1

3

您的函数名称无效(您不能[]在函数名称中包含)尝试更改lbs[i]_Clicklbs_Click.

for(int i = 0; i < 10; i++)
{
    lbs[i] = new Label();
    lbs[i].Location = new System.Drawing.Point(76 + f, 164);
    lbs[i].Size = new System.Drawing.Size(49, 17);
    lbs[i].Name = "label" + i;

    //able to perform this, but wont able to create a method for this
    lbs[i].Click += new System.EventHandler(lbsi_Click);
}

public void lbsi_Click(object sender, EventArgs e)
{
    var label = sender as Label;
    if(label != null && label.Name == "label1"){
        //event was raised from label1
    }
}
于 2012-09-18T15:29:10.630 回答