Sunday, January 7, 2007

ASP .Net UserControl - Static and dynamic loading


A user control (.ascx) can be added to a page by adding the following to the design page ...

<%@ Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<uc1:MyUserControl id="MyUC1" runat="server">uc1:MyUserControl>


In addition to the above method, user controls can also be loaded dynamically at run time using the following UserControl method ...

public Control LoadControl (string virtualPath) 

Here is how to use it in the Page_Load method ...

Control myUserControl = LoadControl("MyUserControl.ascx");

Some pointers for this technique ... - One problem is the lack of positioning control on the final rendered page - One solution is to add the dynamic control in a predefined PlaceHolder control collection - Another problem is that if the user control has output caching enabled, LoadControl returns a reference to PartialCachingControl, which could result in an InvalidCastException - The proper way is to retrieve the user control by using PartialCachingControl.CachedControl