4

我想知道是否有一种动态方法可以避免硬编码 UserControl 或“USING”的引用?

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

我正在寻找一种方法来动态地将对 UserControls 的引用从后面的代码添加到页面。

4

1 回答 1

2

如果我正确理解了你的问题,这应该做你想做的事-

默认.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>

默认.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);
        }
    }
}

用户控件.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(如果 UserControl 是静态的并且不包含特定于解决方案的代码,则不需要)

using System;

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

    }
}

不过,这仅适用于动态添加到页面的控件。

于 2013-03-30T21:32:12.790 回答