标签单击事件

时间:2013-07-31 20:08:12

标签: c# mouseclick-event

我正在尝试为这组动态创建的一组标签创建一个点击事件:

private void AddLBL_Btn_Click(object sender, EventArgs e)
    {
        int ListCount = listBox1.Items.Count;

        int lbl = 0;

        foreach (var listBoxItem in listBox1.Items)
        {
            Label LB = new Label();
            LB.Name = "Label" + listBoxItem.ToString();
            LB.Location = new Point(257, (51 * lbl) + 25);
            LB.Size = new Size(500, 13);
            LB.Text = listBoxItem.ToString();
            Controls.Add(LB);

            lbl++;
        }


       LB.Click += new EventHandler(PB_Click);// error here


    }

    protected void LB_Click(object sender, EventArgs e)
    {



        webBrowser1.Navigate("http://www.mysite/" + LB);//Navigate to site on label

    }

我收到一个错误:“当前上下文中不存在名称'LB'”因为我在循环中创建了LB并且我不够聪明知道如何声明LB所以我可以在循环外使用它

此外,我想将标签名称(listBoxItem)传递给click事件,并将它放在WebBrowser调用中的位置。例如:webBrowser1.Navigate(“http://www.mysite/”+ LB); //导航到标签上的网站

1 个答案:

答案 0 :(得分:7)

您的LB对象超出范围,您需要在循环内移动它。 (此外,您显示的处理程序称为LB_Click,但您正在尝试分配PB_Click;我认为这是一个错字。)

foreach (var listBoxItem in listBox1.Items)
{
    Label LB = new Label();
    LB.Name = "Label" + listBoxItem.ToString();
    LB.Location = new Point(257, (51 * lbl) + 25);
    LB.Size = new Size(500, 13);
    LB.Text = listBoxItem.ToString();
    LB.Click += new EventHandler(LB_Click); //assign click handler
    Controls.Add(LB);

    lbl++;
}

事件处理程序中的sender将是单击的标签。

protected void LB_Click(object sender, EventArgs e)
{
    //attempt to cast the sender as a label
    Label lbl = sender as Label; 

    //if the cast was successful (i.e. not null), navigate to the site
    if(lbl != null)
        webBrowser1.Navigate("http://www.mysite/" + lbl.Text);
}