Dynamic generate control according to the user's operation





2.00/5 (1 vote)
Sep 19, 2007

14230

173
sometimes we need to dynamic generate controls according to the user's operation, such as in a button click event. However, after the post back, the dynamic generated controls would disappear. I use viewstate to keep the infomation of the auto generated controls and generated them at the page load.

Introduction
sometimes we need to dynamic generate controls according to the user's operation, such as in a button click event. However, after the post back, the dynamic generated controls would disappear. I use viewstate to keep the infomation of the auto generated controls and generated them at the page load. Background
Using the code
Unfortunately the WebControl class is unserializable, so I define a serializable class to store the info of dynamic generated controls
[Serializable]
public class ContactControl
However, the genereted controls infomation are stored in the viewstate.
private List<ContactControl> ContactControls
{
get
{
return ReadViewState<List<ContactControl>>("AddedControls", new List<ContactControl>());
}
set
{
ViewState["AddedControls"] = value;
}
}
At every page load, get the genereted controls information and generate them.
protected override void OnLoad(EventArgs e)
{
List<ContactControl> contactControls = ContactControls;
foreach (ContactControl contactControl in contactControls)
{
GenerateControl(contactControl);
}
}