views:

1040

answers:

2

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.

+4  A: 

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.

Steven Robbins
Right you are - thanks!
kristian
A: 

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);
Canavar
Just use LoadControl on the Page.
James