我也尝试为一组动态创建的标签创建一个单击事件,如下所示:
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) 传递给单击事件,并将其放在 WebBrowser 调用中 LB 所在的位置。像:webBrowser1.Navigate("http://www.mysite/ http://www.mysite/" + LB);//导航到标签上的站点
Your 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++;
}
The 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)