Dynamically Load ASP.NET UserControls

Published on
-
1 min read

I had created some .NET UserControl’s that I needed to dynamically add to a Panel control within my page. I previously thought generating my UserControl’s dynamically would be the same as dynamically generating any other .NET Control, like this:

private void CreateControls()
{
    //Create control
    TextBox txtUser = new TextBox();
    txtUser.ID = "txtUser";
    txtUser.Text = "Please enter a value";
 
    //Add Control to Panel already in our .NET page
    pnlControlPlaceHolder.Controls.Add(txtUser);
}

But I was wrong! :-)

Fortunately, there is a really easy way to to add a UserControl dynamically by simply making use of the “LoadControl” method. The “LoadControl” method takes a single parameter containing the virtual path of your UserControl. For example:

private void CreateControls()
{
    //Create control
    Control myUserControl = LoadControl("MyUserControl.ascx") as MyUserControl;
    myUserControl.ID = "ucMyControl";
 
    //Add Control to Panel already in our .NET page
    pnlControlPlaceHolder.Controls.Add(myUserControl);
}

Easy!

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.