kristian
kristian

Reputation: 23049

Programmatically added User Control does not create its child 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.

Upvotes: 2

Views: 2792

Answers (2)

Canavar
Canavar

Reputation: 48088

EDIT : I missunderstood your question,

try this to add your UserControl to your page :

UserControl uc = new UserControl();
uc.LoadControl(Server.MapPath("MyUserControl.ascx");
this.Controls.Add(uc);

Upvotes: 0

Steven Robbins
Steven Robbins

Reputation: 26599

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.

Upvotes: 5

Related Questions