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>

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 (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 に答える