Sunday, January 7, 2007

ASP .Net UserControl - Static and dynamic loading

Static

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>

Dynamic

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");
this.Controls.Add(myUserControl); 

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

Reference

http://msdn.microsoft.com/msdnmag/issues/06/07/webappfollies/default.aspx