Saturday, February 10, 2007

Adding controls to ASP.NET page at runtime

Adding controls to ASP.NET WebForm at runtime is a simple task:

private void Page_Load(object sender, System.EventArgs e)
{
Button newButton = new Button();
newButton.Text = "New Button";
newButton.ID = "newButton";
newButton.Click += new System.EventHandler(this.newButton_Click);

WebUserControl1 newUserControl = (WebUserControl1)LoadControl("WebUserControl1.ascx");
newUserControl.ID = "newUserControl";

this.PlaceHolder.Add(newUserControl);
this.PlaceHolder.Add(newButton);
}

Problem

Now let's raise a bet little. What if we want to add new control as a result of some user action (button click for example)? We are moving the same code from Page_Load to Button_Click event and… Here troubles begin. Our controls will show as expected, but only first time. Any postback will reset page to its original state. Dynamically created controls will be unable to fire any event. What is happening here? The answer is simple. Page class is stateless. It is destroyed after rendering. Page recreates child controls collection, based on tags in aspx file, then postback data can be handled and event handlers attached (in OnInit event). Controls we just created dynamically do not exist in aspx file; page has no knowledge about them.

Solution

Solution is also simple. We have to recreate controls on load stage of page lifecycle. After it's done, each control can handle his postback data, retrieve saved viewstate, raise events etc.

Now code skeleton will look like this:

private void Page_Load(object sender, System.EventArgs e)
{
RecreatePersistedControls();
}
private void Button_Click(object sender, System.EventArgs e)
{
CreateControl("newControl");
PersistControl("newControl");
}
private void RecreatePersistedControls()
{
// Call CreateControl for each persisted control
}
private void CreateControl(string id)
{
// Create controll with specified id,
// add it to controls collection, attach event handlers
}
private void PersistControl(string id)
{
// Persist specified id (in session for example)
}