Click here to Skip to main content
15,878,959 members
Articles / Web Development / ASP.NET

Loading Web User Controls Dynamically in ASP.NET Pages

Rate me:
Please Sign up or sign in to vote.
4.71/5 (11 votes)
3 Oct 2008CPOL3 min read 57.5K   1.7K   18   12
Shows the correct way of loading and rendering web user controls dynamically in ASP.NET pages.

Introduction

The principle of loading web user controls dynamically is easy, that is to use the PlaceHolder control. However, it is not easy to make dynamically loaded controls to work properly if we miss some key points. Detailed information about how to use web user controls dynamically is introduced in this article.

Problem Description

Firstly, remember to use the LoadControl method instead of just creating a new instance of the web user control. Using the new operator to create the instance of the web user control won't work because it just creates the control itself. All the child controls in the created web user control won't be initialized, as we can see in the following figure:

Image 1

In the example above, the HelloWorld web user control contains a button (btnSayHello), a label (lblHello), a required field validator (rfv), and a text box (txtName). We can see that after HelloWorld has been created, no control within it is initialized.

So use the Page.LoadControl method instead of the new operator. The following figure shows the value of the members in the created control, which is much different from the ones we got previously.

2008-10-3_17-09-43.png

After getting the control instance that is returned by the Page.LoadControl method, we can now use the PlaceHolder to render the control. The following line shows how:

C#
PlaceHolder1.Controls.Add(control);

Now you can render the control properly on the page. But what's next? When you want to fire server events in your loaded web user control, you'll find that everything is gone! The control totally disappears when the page is posted back.

What happens? Actually, ASP.NET pages run in the server environment, and it is a stateless object. This means once the page is generated for the client, the instance is disposed. So if we define a local variable in the page object, we cannot get its pervious value when the page is posted back because the page object is pretty new other than the one we first worked with.

In order to correctly render the control even if the page is posted back from the server, we must persist the control so that it can be re-rendered when the page is initializing or loading. It is impossible to persist the entire web user control with the view state or session because the web user control is not serializable. We can persist the virtual path of the control instead, so that the control can be recreated once the proper page events are fired. Don't worry about the state of the fields within the control, they will be maintained by the control itself.

Solution

Now we have the steps for loading and using web user controls dynamically. We can follow these steps which are briefly described below (for detailed solutions, please refer to the attached source files).

  1. Implement a private property for saving and retrieving the saved virtual path of the web user controls.
  2. Implement a private method for creating and loading the web user control according to the saved virtual path. It is important to remember to set the ID for the control; otherwise, the page won't work properly.
  3. In Page_Load event, simply call the method we created in step 2 to recreate the control.
  4. In the Button_Click event, set the private property we created in step 1 to the virtual path of the control that needs to be created and loaded; then call the method we created in step 2 to recreate and load the control.
  5. Override the Dispose method and dispose the controls.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Prosource Development
China China
I have more than 13 years' experience in software development and more than 5 years' working experience in software industry. I'm the National Certified System Analyst and now I'm the consultant of China System Analyst Institution. I also got the MCP/MCAD certificate on .NET technology in the year 2004.
I'm very interested in system architect and analysis, and also interested in .NET technologies. For my blog please refer to http://www.sunnychen.org.

Comments and Discussions

 
QuestionI need Help Pin
exoticankit15-Dec-13 19:06
exoticankit15-Dec-13 19:06 
Questionthank you Pin
DayanidhiTK2-Dec-12 0:46
DayanidhiTK2-Dec-12 0:46 
QuestionThanks Pin
ragavad118-Aug-12 8:46
ragavad118-Aug-12 8:46 
GeneralMy vote of 5 Pin
Member 443048312-Jul-12 1:00
Member 443048312-Jul-12 1:00 
Questionhow do i get values stored in the usercontrol to Javascript Pin
chandruvelan3-Apr-11 20:44
chandruvelan3-Apr-11 20:44 
GeneralReally Good one. Pin
Mazkhan7721-Apr-10 23:01
Mazkhan7721-Apr-10 23:01 
GeneralThanks Pin
Greg Chelstowski11-May-09 22:26
Greg Chelstowski11-May-09 22:26 
GeneralA life saver! Pin
leonbda13-Nov-08 4:50
leonbda13-Nov-08 4:50 
Thanx for this! I wish I was here 5 hours ago...
GeneralThis is how I have always done this... Pin
RK KL3-Oct-08 8:47
RK KL3-Oct-08 8:47 
GeneralRe: This is how I have always done this... Pin
acqy3-Oct-08 14:54
acqy3-Oct-08 14:54 
GeneralRe: This is how I have always done this... Pin
MehdiAnis14-Dec-08 6:28
MehdiAnis14-Dec-08 6:28 
GeneralRe: This is how I have always done this... Pin
Member 768108220-Feb-11 22:20
Member 768108220-Feb-11 22:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.