2

I have following simple controls on a page

WebForm1.aspx

<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<br />
<asp:Label ID="lblContent" runat="server" ></asp:Label>

Some code behind in WebForm1.aspx.cs :

protected void Page_Load(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.ID = "btnTest";
    btn.Text = "I was dynamically created";
    btn.Click += new EventHandler(btnTest_Click);
    Panel1.Controls.Add(btn);
}

void btnTest_Click(object sender, EventArgs e)
{
    lblContent.Text = "btnTest_Click: " + DateTime.Now.ToString();
}

In short, when I dynamically create a Button (btnTest) in the Page_Load event and assign event handler btnTest_Click to the button. Click event then, when loading the page I see btnTest appearing and when clicking on it the event handler btnTest_Click is invoked. OK, No problem.

I have a problem though when I try following scenario... first, I add a button to the page in designer mode.

<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button     ID="btnCreateDynamically" runat="server" 
            Text="Create Button Dynamically" 
                onclick="btnCreateDynamically_Click" />
<br />
<asp:Label ID="lblContent" runat="server" ></asp:Label>

I move the code from Page_Load to the button event handler of btnCreateDynamically as follows

protected void btnCreateDynamically_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.ID = "btnTest";
    btn.Text = "I was dynamically created";
    btn.Click += new EventHandler(btnTest_Click);
    Panel1.Controls.Add(btn);
}

When running the WebApp now and clicking on btnCreateDynamically, btnTest is created but when I click on btnTest its event handler is NOT invoked ???

Why not? How can I make this work?

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
ChrisPeeters
  • 153
  • 2
  • 13

2 Answers2

2

You should add the dynamic controls in the Page's Init event handler so that the ViewState and Events are triggered appropriately.

Try doing this:

protected void Page_Init(object sender, EventArgs e)     
{         
    Button btn = new Button();         
    btn.ID = "btnTest";         
    btn.Text = "I was dynamically created";         
    btn.Click += new EventHandler(btnTest_Click);         
    Panel1.Controls.Add(btn);     
} 
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • What if the controls are to be added on a click event as described in http://stackoverflow.com/questions/14338798/eventhandler-is-not-working-for-dynamic-control ? – LCJ Jan 15 '13 at 13:30
1

You need to re-create dynamic control on each postback, see my previous answer to a similar question here

Community
  • 1
  • 1
Richard Friend
  • 15,800
  • 1
  • 42
  • 60