Adding CheckChanged event handler to CheckBox inside dynamically added UserControl

I have a UserControl that contains a CheckBox and a TextBox:

<asp:CheckBox runat="server" ID="chk1" />
<asp:TextBox runat="server" ID="tb1" />

      

On page_Load, I add a few of these dynamically to the panel on the page:

 //loop through the results from DB
 foreach (Thing t in Things)
 {
    //get the user control
    MyUserControl c1 = (MyUserControl )Page.LoadControl("~/UserControls/MyUserControl.ascx");

    //set IDs using public properties
    c1.ID = "uc" + t.ID;
    c1.CheckBoxID = "chk" + t.ID;
    cl.TextBoxID = "tb" + t.ID;

    //add it to the panel
    myPanel.Controls.Add(c1);

    //add the event handler to the checkbox
    ((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID)).CheckedChanged += new EventHandler(CheckBox_CheckedChanged);   
 }

      

Then I created a method for the event handler on the same page:

protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
       string test = "breakpoint here";
}

      

When I set a breakpoint inside CheckBox_CheckedChanged, it never gets hit when the checkbox changes me.

When I look at the source of the view, this is the code that is generated:

<input id="ctl00_body_uc1_chk1" type="checkbox" name="ctl00$body$uc1$chk1" checked="checked" />

      

So it doesn't seem to get picked up when I add the event handler. This is weird because it all raises everything else.

Did I miss something?

+2


source to share


2 answers


"When I set a breakpoint inside CheckBox_CheckedChanged, it never gets hit when my checkbox is clicked."



If you want the event to fire when the checkbox is clicked, you also need to set AutoPostBack = true in this checkbox. If you put your cursor in a text box and hit "return" (causing the message back), will the event fire happen?

+1


source


Add the CheckBox.AutoPostBack property and set it to "true".



CheckBox cb = ((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID));
if(cb != null)
{
     cb.AutoPostBack = true;
}

      

+2


source







All Articles