简体   繁体   中英

Event handler for dynamically added control does not work

I am adding a dynamic control to my webpage using an update panel. I create an event handler for this dynamic control as well. So although the control is added to the webpage the event handler for this control doesn't work.

my c# code

protected void Button1_Click(object sender, EventArgs e)
{
    CheckBox cbTest = new CheckBox();
    cbTest.Text = "Click me for fun";
    cbTest.AutoPostBack = true; 
    cbTest.CheckedChanged+=new EventHandler(cbTest_CheckedChanged);
    UpdatePanel1.ContentTemplateContainer.Controls.Add(cbTest);
    DynamicPlaceHolder.Controls.Add(cbTest);
}
public void cbTest_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Text = "Yes. It worked!!!";
}

My Aspx code.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <fieldset>
            <legend>UpdatePanel</legend>
            <asp:PlaceHolder ID="DynamicPlaceHolder" runat="server" ></asp:PlaceHolder>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox Width="200px" runat="server" ID="TextBox1"></asp:TextBox>

What happens when i click the button is the check box is created. However when i check the check box the panel just refreshes and the text box is not updated with the text "Yes. It worked!!!".

First, why are you adding the CheckBox to UpdatePanel1.ContentTemplateContainer and even to DynamicPlaceHolder ?

So change it to this:

//UpdatePanel1.ContentTemplateContainer.Controls.Add(cbTest);
DynamicPlaceHolder.Controls.Add(cbTest);

You better assign events in the Page_Load :

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < DynamicPlaceHolder.Controls.Count; i++)
    {
        Control ctrl = DynamicPlaceHolder.Controls[i];
        if (ctrl is CheckBox)
        {
            CheckBox chk = (CheckBox)ctrl;
            chk.CheckedChanged += new EventHandler(cbTest_CheckedChanged);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM