Label Click Event

有些话、适合烂在心里 提交于 2019-12-06 00:21:34

Your LB object is out of scope, you need to move it within the loop. (Also, the handler you've shown is called LB_Click but you're trying to assign PB_Click; I assume that was a typo).

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++;
}

The sender in your event handler will be the label that was clicked.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!