views:

201

answers:

2

I have a an ASPX Page with a Placeholder control declared.

In the Codebehind I create a UserControl I have and add it to the Placeholder.

protected void Page_Load(object sender, EventArgs e)
{
      UserControl uc = new ChartUserControl();
      myForm.Controls.Add(uc);
}

The UserControl in turn has a Placeholder, but in the Page_Load (for the UserControl) when I do:

protected void Page_Load(object sender, EventArgs e)
{
    WebControl x = new WebControl();
    userControlPlaceholder.Controls.Add(x);
}

It gives me the ubiquitous "Object reference not set to an instance of an object" exception.

I've tried forcing instantiation by calling a constructor, but that has gotten me into other trouble. Any help would be appreciated.

+2  A: 

Instead of adding the control in the Page_Load, Override the CreateChildControls method and add it there.

AcousticBoom
Thanks for the tip, makes a lot of sense. Getting exactly the same problem though (I put it after the base.CreateChildControls();).
Chet
+4  A: 

I just spent 4 hours on this myself.

The problem is that you're creating the user controls with

ChartUserControl chart = new ChartUserControl();

but you have to use LoadControl:

ChartUserControl chart =
   (ChartUserControl)LoadControl("~/path/to/control/ChartUserControl.ascx");

Apparently, LoadControl initializes the user control so that its PlaceHolders (and I would assume, other controls it contains), won't be null when you use them.

JeffK
Thank you thank you thank you - this has also got me out of a big pile of doo-doo.
Jeremy McGee
Excellent! I thought I was going to have to rethink my entire approach for this project.
Lill Lansey