Creating Dynamic User Controls

Having known how to create a user control, you should also know how to add it to the web page where it is required. If the page in which the user control is added is not known and you have to dynamically add the user control to the page then you have to use some other method to do it.

To load a user control to the page, you have to use the LoadControl method in the Page_Load event. The LoadControl event takes the name of the user control as its argument and then loads the user control to the page.

Then you can easily add it to the controls collection using the Controls.Add method. However with this you may not know where this user control will be positioned. So you need a placeholder or something like a panel control where you are add the user control.

For example to add the user control dynamically to the placeholder, you can use the following command syntax,

PlaceHolder_Ctrl.Controls.Add(name_of_UserControl);

There are many samples available in the internet on how to add the user control dynamically to the web page.