Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholders Not Instantiated when adding Controls Programmatically

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.

like image 461
Chet Avatar asked Dec 23 '22 10:12

Chet


1 Answers

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.

like image 135
JeffK Avatar answered Dec 29 '22 12:12

JeffK