16. April 2009 18:09
/
0
/
Comments (1)
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!
f4946e7d-3d89-484b-9f83-6e40e35ae756|0|.0|27604f05-86ad-47ef-9e05-950bb762570c