views:

151

answers:

2

I seem to be having an issue getting the event handler for a group of dynamic checkboxes. The code is posted here. I thought this would be pretty straight forward, the checkboxes do not appear in a repeater, datagrid, etc. They appear in a table which is located inside a div which positioned in the center of the screen. Any help would greatly appreciated.

            foreach (SelectAssignedRolesByUserResult role in assignedRoles)
            {
                CheckBox cb = new CheckBox();
                cb.ID = string.Format("CheckBox_{0}_{1}", role.role_nm, role.role_id);
                cb.Text = role.role_nm;
                cb.Attributes.Add("role_id", role.role_id.ToString());
                cb.Attributes.Add("assigned_role_id", role.assigned_role_id.ToString());
                cb.Checked = (role.assigned_role_id > 0);
                cb.CheckedChanged += new EventHandler(cb_CheckedChanged);

                TableCell cell = new TableCell();
                TableRow row = new TableRow();

                cell.Controls.Add(cb);
                row.Cells.Add(cell);
                TableAssignedRoles.Rows.Add(row);
            }
A: 

Can we see some more code? At what point in the lifecycle are you calling the above code?

If you're not recreating the checkboxes in exactly the same way on every postback, such that each Checkbox is assigned the same ID and can load ViewState properly, you'll lose your event handlers.

womp
+1  A: 

You don't mention where the code that dynamically adds the checkboxes is called. I'm guessing you put this in the Page_Load event handler, or in a sub that is called from within Page_Load.

If so, move it from Page_Load to Page_Init.

This is a very non-technical explanation of the reasoning for this:

This is because whether or not the controls are selected happens when the page parses the Viewstate. In the page lifecycle, the Page_Init loads the initial controls, then the viewstate is applied, and then the Page_Load fires.

Added

And don't forget to add

cb.AutoPostBack = true;
David Stratton
i should have just put an answer like yours rather than ask a question, haha. +1 for you then.
Russ Bradberry
Yeah, probably. I did start typing the answer before I saw your comment, so I didn't steal your idea, but I'd give you an upvote had you answered.
David Stratton