Jonas Stawski

Everything .NET and More

Strong Typing a User Control with LoadControl()

We use the Page.LoadControl() method when we have the need to dynamically load User Controls into a page. If you look at the signature of the method the return type is of type System.Web.UI.Control, which is one of the base classes for all controls (directly or indirectly). This is fine when all we want to do is load the User Control, but sometimes we need to reference some properties, methods, events, etc of that control and to do so we have cast the instance of the control to the correct type. The first thing one tries is:

   1: MyUserControl uc = Page.LoadControl("MyUserControl.ascx") as MyUserControl;
   2: //or
   3: MyUserControl uc = (MyUserControl)Page.LoadControl("MyUserControl.ascx");

but this results in the compile time error of type System.Web.HttpCompileException: “The type or namespace name ‘MyUserControl’ could not be found (are you missing a using directive or an assembly reference?).”

To fix this all we have to do is register the UserControl with the page by adding the following Register declarative in the aspx page:

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="uc1" %>

Happy programming!

Comments (1) -

Nice post,

A very interesting article,

Keep up the good work



Add comment