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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With