Placeholder is not created when adding controls programmatically

I have an aspx page with declared placeholder control.

In Codebehind, I create a UserControl that 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 user, in turn, has a Placeholder, but in Page_Load (for UserControl), when I do this:

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

This gives me the ubiquitous exception, "An object reference not set to an instance of an object."

I tried to create an instance by calling the constructor, but this caused me other problems. Any help would be appreciated.

+4
source share
2 answers

I just spent 4 hours on it myself.

The problem is that you are creating custom controls with

 ChartUserControl chart = new ChartUserControl(); 

but you have to use LoadControl:

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

Apparently, the LoadControl initializes the user control so that its PlaceHolders (and I would suggest that the other controls it contains) will not be null when you use them.

+8
source

Instead of adding a control to Page_Load, override the CreateChildControls method and add it there.

+2
source

All Articles