Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Dynamically Loading User Control on a Webform using PlaceHolder control

0.00/5 (No votes)
5 Aug 2004 1  
Dynamically loading a User Control on a webform using PlaceHolder control.

Introduction

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 Page_Load event.

if(!Page.IsPostBack) 
{ 
    WebUserControl1 uc = 
      (WebUserControl1) Page.LoadControl("WebUserControl1.ascx"); 
    PlaceHolder1.Controls.Add(uc); 
}

Here in the code, WebUserControl1 is the name of the UserControl class through which we have created an instance namely "uc". The 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.

Conclusion

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here