Can't Get Enough RSS 2.0
 Thursday, January 17, 2008

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;

}

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);

}

 

 

Run the code, and test it your self.

 

To download a sample project click the below link:

LoadDynamicWebUserControl.zip (3.23 KB)
Thursday, January 17, 2008 1:16:50 PM UTC  #    Comments [0] -
ASP.NET | C#
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
Navigation
Categories
Archive
<January 2008>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Ghazi Sarhan
Sign In
Statistics
Total Posts: 13
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2010, Ghazi Sarhan
DasBlog theme 'Business' created by Christoph De Baene (delarou)