Search code examples
c#asp.netuser-controlspage-lifecycle

Adding a control to a panel gives me "Object Reference not set to an instance of the object" error


Trying to dynamically add a user control that dynamically generates content. The User Control cannot get a handle on the panel to put controls in.

First I have a page (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>

code behind:

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();
    }
}

and then here is the user control:

    <asp:Panel ID="pnlTest" runat="server" >
    </asp:Panel>

and the code behind:

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);
    }
}

So... It seems like the point at which I'm calling Fill() is before the user control has been rendered, therefore pnlTest has not been instantiated. But, I'm not sure where to call uc.Fill() from test.aspx ... I tried Page_PreRenderComplete, but that didn't work either...

(if you see a name mis-match.. that's probably not the error... the names have been changed to protect the innocent)


Solution

  • hurray, I can answer my own question. I changed test.aspx.cs to this:

    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();
        }
    }