Loading WebUserControls `.ascx` files at runtime gives you the ability to create a dynamic page, the ability to create a page that accept plugins.
The problem is when you load WebUserControl at runtime, any postback caused by the page or the control itself will cause the control to disappear, here is a simple way explaining how to load these controls and maintaining them after postback.
First create two WebUserControls as shown below:
In the Save Button's code behind for both controls, write the following code:
protected void butSave_Click(object sender, EventArgs e){ Label1.Text = TextBox1.Text;}
{
Label1.Text = TextBox1.Text;
}
Then create an `aspx` page with three Buttons and a Panel on the page as shown below:
Write the following code in page's code behind:
protected void Page_Load(object sender, EventArgs e){ if (ViewState["myControl"] != null && ((string)ViewState["myControl"]) != string.Empty) { UserControl uc = LoadControl(ViewState["myControl"] + ".ascx") as UserControl; uc.ID = ((string)ViewState["myControl"]); // Do not clear Panel1's controls in `Page_Load` using `Panel1.Controls.Clear()` // in some cases the control's viewstate will be lost. Panel1.Controls.Add(uc); }} protected void butLoadControl1_Click(object sender, EventArgs e){ ViewState["myControl"] = "WebUserControl1"; UserControl uc = LoadControl("WebUserControl1.ascx") as UserControl; uc.ID = "WebUserControl1"; Panel1.Controls.Clear(); Panel1.Controls.Add(uc);} protected void butLoadControl2_Click(object sender, EventArgs e){ ViewState["myControl"] = "WebUserControl2"; UserControl uc = LoadControl("WebUserControl2.ascx") as UserControl; uc.ID = "WebUserControl2"; Panel1.Controls.Clear(); Panel1.Controls.Add(uc);}
uc.ID = ((
// in some cases the control's viewstate will be lost.
Panel1.Controls.Add(uc);
ViewState[
uc.ID =
Panel1.Controls.Clear();
Run the code, and test it your self.
To download a sample project click the below link:
Remember Me
a@href@title, strike
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.