Dynamic user control list
How do you add and remove user controls dynamically on an ASP.NET page?
There are many ways to do this and here I will present one.
The page container
Start with adding a button and a placeholder on the page. The button will create user controls in the placeholder.
The user control
The user control is very simple. The delete button is tied to an event that will call the Delete-method on the current page.
The IDynamicControlContainer interface
If you want this to work you need to create an interface that has the Delete-method, and implement this interface on the container page. The reason you want the method on an interface and not on the container page, is to create lower coupling from the user control on the container page.
Keep state between post backs
We will use the ViewState to save and restore state between postbacks. The only thing we need to keep track on our selves is the control IDs that we added to the user control. When we return on postback, we recreate the controls in the placeholder with the previous IDs and trust that ASP.NET will read back the state of these controls for us. When we change the list by adding and removing a control, we also update the list of IDs in ViewState. Here comes my code behind for the container page.
protected void AddButton_Click(object sender, EventArgs e)
{
Create(null);
}
public void Create(string id)
{
string targetId = id ?? Guid.NewGuid().ToString();
var control = LoadControl("~/NameControl.ascx");
control.ID = targetId;
DynamicNameList.Controls.Add(control);
SaveControlIdList();
}
public void Delete(Control control)
{
DynamicNameList.Controls.Remove(control);
SaveControlIdList();
}
public void SaveControlIdList()
{
List idList = new List<string>();
foreach (Control control in DynamicNameList.Controls)
{
idList.Add(control.ID);
}
ViewState["IdList"] = idList;
}
public string[] LoadControlIdList()
{
var list = (List<string>) ViewState["IdList"];
if (list == null)
{
return new string[0];
}
return list.ToArray();
}
}
You can download the complete source code sample here.