C# 标签单击事件

C# 标签单击事件,c#,mouseclick-event,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 = ne

我也在尝试为动态创建的一组标签创建一个单击事件,如下所示:

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调用中LB所在的位置。比如:webBrowser1.导航(“+LB”)//导航到标签上的站点

您的
LB
对象超出范围,您需要在循环中移动它。(另外,您显示的处理程序名为
LB_-Click
,但您正在尝试分配
PB_-Click
;我认为这是一个打字错误)

事件处理程序中的
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);
}

我在foreach循环中添加了LB.Click+=neweventhandler(PB_Click),现在它可以正常工作了。另外,webBrowser1.Navigate(“+lbl.Text”);也很好。谢谢
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);
}