以编程方式创建用户控制实例

如果要在页面后面的 ASPX 代码中实例化用户控件实例,则需要在 Page_Load 事件上编写用户控件声明,如下所示:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(Object sender, EventArgs e)
    {
        Control control1 = LoadControl("UserControl.ascx");
        Page.Controls.Add(control1);
    }
}

请注意,执行 LoadControl 方法时应该已经创建了用户控件 ASCX 文件。

另一种以编程方式声明用户控件的方法是使用 PlaceHolder

public partial class Default : System.Web.UI.Page
{
    public PlaceHolder Placeholder1;
    protected void Page_Load(Object sender, EventArgs e)
    {
        Control control1 = LoadControl("UserControl.ascx");
        Placeholder1.Controls.Add(control1);
    }
}

根据你的需要,PlaceHolder 将用户控件放在一个容器中,该容器存储动态添加到页面中的所有服务器控件,其中 Page.Controls 直接在页面内插入用户控件,这更适合呈现 HTML 文字控件。