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开发者_JAVA技巧, 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);
}
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;
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.
精彩评论