Home > c#, Code > Dynamically creating user controls in code behind

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.

Advertisements
Categories: c#, Code Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: