Dynamically Load a user control (ascx) in a asp.net website

后端 未结 6 1294
情话喂你
情话喂你 2020-12-09 06:41

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

6条回答
  •  时光说笑
    2020-12-09 06:56

    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.

提交回复
热议问题