elt*_*910 3 c# mouseclick-event
我正在尝试为一组动态创建的标签创建一个click事件,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:"当前上下文中不存在名称'LB'"因为我在循环中创建了LB而且我不够聪明知道如何声明LB所以我可以在循环之外使用它.
另外,我想将标签名称(listBoxItem)传递给click事件,并将它放在WebBrowser调用中的位置.喜欢:webBrowser1.Navigate(" http://www.mysite/ "+ LB); //导航到标签上的网站
您的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++;
}
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)