Dynamically Adding User Controls to an ASPX page

This code example is used to demonstrate how to load ASP.NET user controls to a page dynamically. At the end of this post you can download the sample project.

The screen shot below contains three makes of cars Ford, Chevy, and Dodge and asks users to pick a model and type in some comments.  This is actually one user control added to the page dynamically three times. 

Here is a screen shot of the user control. 

Adding The Control to the ASPX Page

When you add the control the parent page, This is Key, you must do the load from the Page_Init() method.  This way it will get added to the viewstate of the site. If you add it in Page_Load() for example you will not be able to get the values of the user control in the Save() method. 

The AddControlToPage() method will call the user control multple times to load the values.

Loading The Control

The user control has a SetupControl() method that accepts two parameters.   The first one tells the user control to load values from the database, and the second value is the vehicle manufacturer.

The reason for the "load from database" flag is that when you load a user control dynamically you need to populate values of labels and drop down items after each post-back.  You only want to pull from the database on the first load of the page.  On all subsequent page loads you still need to load all the items to the drop down but you do not want to override any user input.   No worries, when you reload the drop downs ASP.NET remembers the user last selection.   The point of reloading the drop down is to get all the values back in the drop down list. 

The point to remember about adding controls to the page dynamically is to do this from the Page_Init method.  You can spend a good deal of time wondering why you cannot get to the values of the control or why the values entered in text boxes are gone when attempting to perform the load outside of Page_Init.


DynamicUC.zip (173.99 kb)

Comments are closed