问题
I am trying too create a click event for a group of lables that are created dynamically like this:
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
}
I am getting an error: "The name 'LB' does not exist in the current context" becauseI am creating LB within the loop and I am not smart enough to know how to declare LB so I can use it outside the loop.
Additionally, I would like to pass to the label name (listBoxItem) on to the click event and have it where LB is in the WebBrowser call is. Like: webBrowser1.Navigate("http://www.mysite/" + LB);//Navigate to site on label
回答1:
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);
}
来源:https://stackoverflow.com/questions/17979929/label-click-event