开发者

Dynamic creation of Button OK but its event handler NOT executed?

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 btnCreateDynamica开发者_开发问答lly 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜