开发者

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

开发者 https://www.devze.com 2023-04-13 04:57 出处:网络
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.

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>
</开发者_如何学Pythonhead>
<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)


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


I had a similar issue. Turns out the system could not find a reference to the object because it had not been structured/included in the [filename].aspx.designer.cs file.

Stopping the code to add the panel and then re-building the solution should ensure this reference is added, which should fix the object reference exception issue.


Similar issue in Windows Forms app - Needed to add

using SomeDllInMyProject;

to the form code. Even though the project had a reference to the DLL, the ref needed to be in the form code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号