Dynamic Creation of User Controls
Posted: 5/2/2008 11:21:32 AM
By: Comfortably Anonymous
Times Read: 1,781
0 Dislikes: 0
Topic: Programming: Web Applications

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)