In this article, I will explain how to load UserControls programmatically on your webform. First, drag and drop a PlaceHolder control on your webform on which you will load the actual UserControl.
Adding Directive on a Webform
First, you need to add a directive on a webform telling the webform that you are going to dynamically load the usercontrol. So in the webform, add the following directive:
<%@ Reference Control = "WebUserControl1.ascx" %>
Once this directive has place, you need to load the actual control in the webform. You can load the control anywhere in the form. A good place will be the
Page_Init event. In the example, I have loaded the control in the
WebUserControl1 uc =
Here in the code,
WebUserControl1 is the name of the UserControl class through which we have created an instance namely "
Page.LoadControl loads the control on the page. And finally the place holder control adds the control to its collection and displays it on the webform.
You can always use drag and drop features of the usercontrol to include it on the page. But sometimes it's important to load when some event occurs in the application, and for that you can create the controls dynamically.