Label Click Event

eltel2910 picture eltel2910 · Jul 31, 2013 · Viewed 21.2k times · Source

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

Answer

keyboardP picture keyboardP · Jul 31, 2013

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