View Light

Dynamic Creation of User Controls

Instantiating a new user control is not as straightforward as you'd think. The logical approach would be like:

UserControl control = new UserControl();
this.Page.Controls.Add(control);

Unfortunately, this does not work. While you've technically got an instantiated UserControl object, none of the controls that should be contained by the user control will be there - they will all be null. Why, not quite sure. But at least there's an alternate approach.

You have to use the LoadControl method:

UserControl control = LoadControl(”~/MyControls/UserControl.ascx”) as UserControl;
this.Page.Controls.Add(control);


This way you get a fully fleshed-out UserControl with all the child controls.

Rating: (You must be logged in to vote)
Reply