views:

90

answers:

2

I have some code which involves dynamically creating new buttons, when a user clicks on a particular button. However the EventHandlers defined for these dynamically created buttons do not execute when I click on any one of them. Here is the errant code snippet:

protected void Page_Load(object sender, EventArgs e)
{
    .......
    btn1.Click += new EventHandler(this.btn1_Click);
    .......
}

protected void btn1_Click(object sender, EventArgs e)
{
    .......
    LinkButton btn2 = new LinkButton();
    btn2.Click += new EventHandler(this.btn2_Click);
    .........
}

protected void btn2_Click(object sender, EventArgs e)
{
    .......
}

The code execution never enters btn2_Click(). Am I doing something wrong here?

+1  A: 

Try declare LinkButton btn2 as global variable and and wire the event btn2.Click += new EventHandler(this.btn2_Click) as the controls are created.

Eduardo Xavier
A: 

btn2 disappears as soon as you leave the btn1 event handler. It's a local variable, and goes away as soon as it's out of scope.

Did you ever see the second button? Did you click on it? If so, then you clicked on the wrong button. This one you added never appeared on your page.

In order for a control to become visible (and to render into HTML), it must be placed inside of the Controls collection of a visible control. You're not doing anything with it.

John Saunders