简体   繁体   中英

How to avoid hard-coding the Reference for a UserControl?

I'd like to know whether or not there is a dynamic way to avoid hard-coding the Reference for a UserControl or by "USING"?

<%@ Reference Control="~/UserControl.ascx" %>
using UserControl;

I'm seeking a way to dynamically add References to UserControls to the page from code behind.

If I have understood your question correctly, this should do what you want to do-

Default.aspx

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Dynamic User Control Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Dynamic User Control Test</h1>
        <asp:PlaceHolder ID="UserControlPlaceHolder" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        UserControl uc = Page.LoadControl("~/UserControl.ascx") as UserControl;

        if (uc != null)
        {
            UserControlPlaceHolder.Controls.Add(uc);
        }
    }
}

UserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>

<p>Here is some content inside the user control</p>

UserControl.ascx.cs (this isn't needed if the UserControl is static and contains no solution specific code)

using System;

public partial class UserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

This will only work with controls that are dynamically added to the page though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM