Asp.net 在cs类中创建不是aspx页代码隐藏的用户控件实例

Asp.net 在cs类中创建不是aspx页代码隐藏的用户控件实例,asp.net,user-controls,Asp.net,User Controls,我正在asp.net中编写一个应用程序, 我编写了一个web用户控件(位于\WebSite\UserControls\StudentAddressingTeacherUserControl.ascx文件夹中) 现在我想在一个类中创建这个用户控件的一个实例(不是aspx页面的代码块的cs) 我如何才能做到这一点?为什么要创建实例,是否要将其动态添加到页面 public static void addStudentAddressingTeacherUserControl() { Page p

我正在asp.net中编写一个应用程序, 我编写了一个web用户控件(位于\WebSite\UserControls\StudentAddressingTeacherUserControl.ascx文件夹中)

现在我想在一个类中创建这个用户控件的一个实例(不是aspx页面的代码块的cs)


我如何才能做到这一点?

为什么要创建实例,是否要将其动态添加到页面

public static void addStudentAddressingTeacherUserControl()
{
    Page p = HttpContext.Current.CurrentHandler as Page;
    if (p != null)
    {
        var path = "~/UserControls/StudentAddressingTeacherUserControl.ascx";
        var control = p.LoadControl(path);
        p.Controls.Add(control);
    }
}
你也可以简单地

Control c = (this).LoadControl("/UserControls/StudentAddressingTeacherUserControl.ascx");

为什么要创建实例,是否要将其动态添加到页面?是的,我需要动态添加,但我需要在一个类(.cs)中创建实例,该类不是aspx代码,因此我没有页面。load@user723686字体恐怕你不明白我的方法。我通过
HttpContext.current.CurrentHandler
获取当前页面,它甚至可以在静态方法中使用(如本例中)。只要您在HttpContext中(而不是在Winforms应用程序中),并且不使用ASHX处理程序而不是ASP.NET页面,这就可以工作。您甚至可以将此方法放在单独的类库dll中,并且可以在任何需要的地方调用它(例如自定义类)。