C# – Programmatically added User Control does not create its child controls

asp.netcuser-controls

I have a user control (.ascx) in my project that I am adding to a page programmatically in the page's Page_Load event handler, like so:

Controls.Add(new MyProject.Controls.ControlWidget());
Databind();

When I try to access the control's child controls from within the control itself, they do not exist.

public override void DataBind()
{
  myrepeater.DataSource = GetDataSource(); 
  // throws an exception because myrepeater is null

  base.DataBind();
}

How do I access the user control's child controls? I have tried adding a call to EnsureChildControls() to my DataBind() override but that doesn't seem to make a difference.

Best Answer

You need to use LoadControl to load it, not just instantiate the class. LoadControl does "magic" behind the scenes to tie everything up and instantiate the front end.

Related Topic