Dynamically creating user controls in code behind

If you have a user control that you wish to dynamically add to your page the following will not work;
[csharp]
UserControl control = new UserControl()
[/csharp]
The problem is that the control has not been successfully created and all the internal controls that make up the user control, like text boxes etc, will be null.

The way to create the control is with the “LoadControl()” statement.
[csharp]
UserControl control = LoadControl("~/controls/UserControl.ascx") as UserControl;
[/csharp]
and now it will work.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.