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 d
It can easily be done using namespaces. Here's an example:
WebControl1.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebControl1.ascx.cs" Inherits="MyUserControls.WebControl1" %>
Notice that Inherits references the namespace (MyUserControls), and not just the class name (WebControl1)
WebControl1.ascx.cs:
namespace MyUserControls
{
public partial class WebControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Notice that the class have been included in the namespace MyUserControls
Default.aspx.cs:
using MyUserControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var control = (WebControl1) Page.LoadControl("~/WebControl1.ascx");
}
}
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.