向面板添加控件使我"对象引用未设置为对象的实例"错误

mat*_*360 2 c# asp.net user-controls page-lifecycle

尝试动态添加动态生成内容的用户控件.用户控件无法获取面板上的控件以放置控件.

首先我有一个页面(test.aspx):

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

代码背后:

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TestUserControl uc = new TestUserControl();
        Panel1.Controls.Add(uc);
        //this is where the error happens:
        uc.Fill();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后这是用户控件:

    <asp:Panel ID="pnlTest" runat="server" >
    </asp:Panel>
Run Code Online (Sandbox Code Playgroud)

和背后的代码:

public partial class TestUserControl: System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public void Fill()
    {
        Label lbl = new Label();
        lbl.Text = "test";
        //This is where pnlTest is null and I get "Object Reference Not Found..."
        pnlTest.Controls.Add(lbl);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以......在调用用户控件之前,我正在调用Fill()的点似乎尚未实例化pnlTest.但是,我不知道在哪里从test.aspx调用uc.Fill()...我尝试了Page_PreRenderComplete,但这也不起作用......

(如果你看到一个名字不匹配......这可能不是错误...名称已被更改以保护无辜者)

mat*_*360 8

欢呼,我可以回答我自己的问题.我将test.aspx.cs更改为:

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        TestUserControl uc = (TestUserControl)Page.LoadControl("~/UserControls/TestUserControl.ascx");
        Panel1.Controls.Add(uc);
        uc.Fill();
    }
}
Run Code Online (Sandbox Code Playgroud)