Dynamically Load ASP.NET UserControls

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!


Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself. :-)