Dynamically load user control in ASP.NET Webform
User Controls are semi-autonomous pages of HTML and underlying ASP.NET code that can be inserted into ASP.NET pages. As such they are useful for adding blocks of functionality to pages. Typical uses are to use User Controls for page headers and footers. They can also add functionality such as a "property of the week" for a real estate company website.
Unlike ASP.NET pages that have the .aspx file extension, User Controls typically have the .ascx file extension. Once created, in Visual Studio.NET they can be included in a specific page by simply dragging the user control onto the design view of that page. Alternatively, they can be added to a page at design time by including the following in the page's HTML. For example, the following line includes a header user control from the HeaderUserControl.ascx file:
<%@ Register TagPrefix="uc1" TagName="HeaderUserControl" Src="HeaderUserControl.ascx" %>
The header is then positioned on the page using the following tag:
Although this procedure is satisfactory for content like headers and footers that will always be required on specific pages, it would be useful if there was a way of dynamically loading specific user controls at run time. For example, an online store may only want a "clearance offers" section to appear if there is actually stock inventory in the database that has been marked as being for clearance.
Fortunately, it is possible to load user controls onto a page by making use of the LoadControl method. This function has a straightforward syntax - it takes a single argument - the virtual path to the user control page. For example, to load the featured product user control the following C# code would be used within the Page_Load method:
Control FeaturedProductUserControl = LoadControl("FeaturedProduct.ascx");
Once the user control has been loaded, it can be added to the page by adding it to the Controls collection:
Controls.Add(FeaturedProductUserControl);
The drawback with this technique is that it offers no control over where on the page the user control will actually appear. A useful tip is, therefore, to add a place holder control to the page in the position that you want it to display the dynamically loaded user controls. A place holder does just that - it acts as a container for other controls. You can then specify that the user control appear within the place holder by adding the user control to the place holder's controls collection:
PlaceHolderLeftMenu.Controls.Add(FeaturedProductUserControl);
Alternatively it is possible to position the user control in other ways, such as adding it to a Panel control:
PanelRightMenu.Controls.Add(FeaturedProductUserControl);