views:

746

answers:

2

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'm adding several of them dynamically them to a 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);   
 }

I then created the method for the event handler in the same page:

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

When I put a breakpoint inside CheckBox_CheckedChanged it's never hit when the my checkbox gets clicked.

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

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

So, it doesn't seem to be picking up when I add the event handler. It's weird, cause it picks up everything else though.

Am I missing something?

+1  A: 

"When I put a breakpoint inside CheckBox_CheckedChanged it's never hit when the my checkbox gets clicked."

If you want the event to fire when the check box gets clicked, you also need to set AutoPostBack = true on the check box. If you put the cursor in the text box and press return (causing a post back), does the event fire?

pjabbott
Yep. That was it. Thank you!
Ozzie Perez
+1  A: 

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;
}
rick schott
Of course! Thank you.
Ozzie Perez