3

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

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 事件,并将其放在 LB 在 WebBrowser 调用中的位置。like: webBrowser1.Navigate(" http://www.mysite/ " + LB);//导航到标签上的站点

4

1 回答 1

9

您的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);
}
于 2013-07-31T20:13:19.497 回答