Checkbox Changed Event not firing for dynamically added control
I have created a 3 checkboxes in my jQuery accordion control dynamically in the page load event and I am also associating the CheckedChanged Event for the textbox. But the event is not firing at all. I am not sure what is happening here. Please help me. Thanks and appreciate your feedback.
Code that I used to generate dynamic control and associate the event
protected void Page_Load(object sender, EventArgs e)
{
dvAccordion.Controls.Clear();
foreach (DataRow row in dataSetIP.Tables[0].Rows)
{
HtmlGenericControl tt= new HtmlGenericControl("H3");
HtmlAnchor anc= new HtmlAnchor();
HtmlGenericControl dvP= new HtmlGenericContr开发者_C百科ol("DIV");
dvP.InnerHtml = row["LD"].ToString();
CheckBox chkTest = new CheckBox();
if (!Page.IsPostBack) chkTest .ID = "chk" + row["SD"].ToString();
else
{
string uniqueID = System.Guid.NewGuid().ToString().Substring(0, 5);
chkTest .ID = "chk" + uniqueID + row["SD"].ToString();
}
chkTest.Text = row["SD"].ToString();
chkTest.AutoPostBack = true;
chkTest.CheckedChanged += new EventHandler(chkTest _CheckedChanged);
chkTest.InputAttributes.Add("Value", row["ID"].ToString());
anc.Controls.Add(chkTest);
tt.Controls.Add(anc);
dvAccordion.Controls.Add(tt);
dvAccordion.Controls.Add(dvP);
}
}
But the CheckboxChanged event is not firing.
It's an issue of when you add the control, ViewState, and some of the lifecycle. Dynamically adding controls that fully participate in the whole lifecycle is a complicated subject, and without more context, it's best for you to read the Truly Understanding Dynamic Controls series.
In your case, I think you're re-creating the control on the next page load after the ViewState initialization, so it doesn't know about the binding at the time it needs to queue up the call to your bound event handler.
Try adding the controls in the Page_Init()
event (which is fired before the Page_Load()
event).
精彩评论