I am trying to dynamically load a user control in an asp.web site. However due to how asp.net websites projects are setup (I think), I am not able to access reach the type definition of the user control.
I get a message saying that my class HE_ContentTop_WebControl1 is: he type or namespace name 'HE_ContentTop_WebControl1' could not be found (are you missing a using directive or an assembly reference?)
Any idea how this could be made to work ? I have attempted using namespace but it seems to me that asp.net websites are not designed to work with namespaces by default. I would be interested in a non namespace approach.
TIA
public partial class HE_Default :
System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
var control = (HE_ContentTop_WebControl1)Page.LoadControl("~/ContentTop/WebControl1.ascx");
}
}
The subject of this post is a bit misleading. If you just want to add a control dynamically, you will not have to reference the control and therefore you can just add it with something simple like:
without any namespace hassel.
Casting the user control this way may create many problems .my approach is to create a class (say control Class) put all the properties and method you need for casting in it and inherit this class from System.Web.UI.UserControl .Then in your user cotrol code file instead of System.Web.UI.UserControl user this control class .
now when ever you need casting, cast with this class only . it will be light casting as well.
Assuming the control exists in the same assembly as your web project, you need to add a reference directive in your .aspx file,
e.g:
Keep in mind it often takes a few minutes (or sometimes a build) for IntelliSense to pick this up.
Namespaces are not supported under the website model. As such, I could not get any of the solutions proposed to work. However, there is a solution. Create an interface and place it into app code and then implement the interface in the user control. You can cast to the interface and it works.
the reference is not enough using
in the aspx file is just one part of the answer.
you need also to add the calssName in the User Control aspx file
and then you can use the userontrol in your aspx file
It can easily be done using namespaces. Here's an example:
WebControl1.ascx:
Notice that Inherits references the namespace (MyUserControls), and not just the class name (WebControl1)
WebControl1.ascx.cs:
Notice that the class have been included in the namespace MyUserControls
Default.aspx.cs:
This approach potentially allow you to redistribute your user controls (or keep them in a separate project) without the hassle of referencing them in your .aspx files.