Sacha Tomey

Sacha Tomey's Blog

LoadControl Changes in .NET 2.0

In .Net 1.x you can dynamically load user controls using the Page.LoadControl member.  Providing you namespace your classes the same or qualify the classes correctly you can cast the return value of LoadControl to an object of your user control type.
 
MyUserControl myUserControl = (MyUserControl )LoadControl("MyUserControl.ascx");
MyFolderedUserControl myFolderedUserControl = (MyFolderedUserControl )LoadControl("Folder/MyUserControl.ascx");
 
Moving to .Net 2.0, where namespaces are no longer a key reference mechanism, an additional step is required.
 
In the partial code behind class, specify the loading and casting as you would in Net 1.x.
 
MyUserControl myUserControl = (MyUserControl)LoadControl("MyUserControl.ascx");
MyFolderedUserControl myFolderedUserControl = (MyFolderedUserControl)LoadControl("Folder/MyUserControl.ascx");
 
However, when you attempt to compile this code, the second line will fail, this is because the foldered user control is not part of the main assembly and the compiler knows nothing about it.  To fix this you need to add a reference attribute to the aspx file that will host the user control:
<%@ Reference Control="Folder/MyUserControl.ascx" %>
Loading