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;

UserControl control = new UserControl()

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.

UserControl control = LoadControl("~/controls/UserControl.ascx") as UserControl;

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.