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?

2 Answers 2

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);     
} 
Sign up to request clarification or add additional context in comments.

1 Comment

What if the controls are to be added on a click event as described in stackoverflow.com/questions/14338798/… ?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.