Wednesday, March 28, 2012

Dynamic Control creation not persisting through PostBack

Hey guys,

I've done some searching on dynamic control creation in the forums, but none of them take me to an Atlas page. I'm trying to build a HR Notification form with some simple Atlas UpdatePanels. Basically, I want to dynamically add Labels and TextBoxes to this form. For instance, if you select 3 from the Number of Children DDL, I want 3 child forms to be created under it. I've been able to create the forms (at least theoretically, I just create "test" Labels right now). The problem I'm running into is being able to read from these dynamically created Controls.

When I submit the form as a regular PostBack, all of my created labels seem to be lost. I get null exceptions when I try to use FindControl. Here are some code snippets:

protected void ddlNumChildren_SelectedIndexChanged(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label text=new Label(); text.ID ="testLabel" + count; text.Text ="test"; phNumChildren.Controls.Add(text); count++; } }protected void btnSubmit_Click(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label lbltest = phNumChildren.FindControl("testLabel" + count)as Label; Response.Write(lbltest.Text); } }

I'm assuming I have to save this data before the postback, but I need a little help in how I can do this. Thanks for your time and any help you can provide.

The problem is that the controls do not exist when the page is recreated during postback. You have two options :
1) Recreate the page during the Init() event if you have atlas UpdatePanels or Page_Load() if not
2) try http://www.denisbauer.com/ASPNETControls.aspx
3) Write your own code to save all controls in ViewState and reload them during the Init() event

No comments:

Post a Comment