1

我在表单上有很多标签,每个标签都使用不同的参数调用相同的方法(属于标签文本/名称)。这是代码:

    //"res" is an array
    private void label1_Click(object sender, EventArgs e)
    {                       
        checkresult(res[0]);
    }

    private void label2_Click(object sender, EventArgs e)
    {        
        checkresult(res[1]);
    }

    private void label3_Click(object sender, EventArgs e)
    {  
        checkresult(res[2]);
    }

    private void label4_Click(object sender, EventArgs e)
    { 
        checkresult(res[3]);
    }

    private void label5_Click(object sender, EventArgs e)
    {
        checkresult(res[4]);
    }

    private void label6_Click(object sender, EventArgs e)
    {
        checkresult(res[5]);
    }

    private void label7_Click(object sender, EventArgs e)
    {
        checkresult(res[6]);
    }

    private void label8_Click(object sender, EventArgs e)
    {
        checkresult(res[7]);
    }

    private void label9_Click(object sender, EventArgs e)
    {
        checkresult(res[8]);
    }

我只想通过为所有标签定义一种方法来精确我的代码。我该怎么做?

4

4 回答 4

4

伪代码可能如下所示:

label1.Click += label_Click(object sender, EventArgs e); 
label2.Click += label_Click(object sender, EventArgs e);//SAME HANDLER
label3.Click += label_Click(object sender, EventArgs e);//SAME HANDLER
....

之后

private void label_Click(object sender, EventArgs e)
{
    if(sender == label1)
      checkresult(res[0]);
    else if(sender == label2)
      checkresult(res[1]);
   ... 
   ...
}
于 2013-01-09T08:32:14.553 回答
3

首先让所有标签使用相同的Label_Click事件。

private void Label_Click(object sender, EventArgs e)
{
    Label temp = sender as Label;
    if (temp != null)
    {
        string labelName = temp.Name;
        string labelId = labelName.Substring(5, labelName.Length);
        int id = int.Parse(labelId) - 1;
        checkresult(res[id]);
    }                
}
于 2013-01-09T08:35:02.267 回答
1

您可以在创建事件处理程序时设置匿名委托

label1.Click += (s,e) => {checkresult(res[0]); };
label2.Click += (s,e) => {checkresult(res[1]); };
label3.Click += (s,e) => {checkresult(res[2]); };
于 2013-01-09T08:41:41.287 回答
0

在 WinForms 中,将您的索引设置为标签标签并将每个 OnClick 事件设置为相同的 EventHandler

 private void lbl_Click(object sender, EventArgs e)
 {
      checkresult(res[Convert.ToInt32((sender as Label).Tag)]);
 }
于 2013-01-09T08:34:51.520 回答