There are a few things to keep in mind when you create controls on the fly and add them to your page. Simply put, you want to add them to the page hierarchy as soon as possible. Before they are added to the page, they have not initialized themselves. When a dynamic control is added to another control, the new control plays catch-up to get to the stage that the parent control is in. For instance, if in your Page_Load, you add a textbox, it will play catch-up and go through its Init and Load phases. This is important beceause it will start tracking its viewstate. Values added before it is tracking viewstate won’t make it to viewstate and will be lost on PostBack. Here is an example that won’t work:
TextBox txt = new TextBox();
if(!IsPostBack)
{
txt.Text = “test value”;
}
this.Form1.Controls.Add(txt);
This example shows setting a text property BEFORE this control is added to the page (and before it is tracking viewstate). Next, we’ll show the right way to do it:
this.Form1.Controls.Add(txt);
if(!IsPostBack)
{
txt.Text = “test value”;
}
Note here that we add the control to the page BEFORE we set a property. This enables our dynamic control to participate in viewstate as well as the rest of the page lifecycle.
To clarify, if we add a dynamic control during the Page’s PreRender, when we do the Controls.Add( ) function, the new control will go through Init, Load and PreRender immediately to catch up with its parent (the Page).