Dynamically Load Web Controls at Run Time

Hi, Randy Evans here. I’m a principal developer on the Information Security Tools team.

On one of our projects we had a requirement to dynamically load different web parts into a web page at run time. The challenge was that the specific web part needing to be loaded was determined by the user’s action on the web page. Thus, we couldn’t directly reference the web part in the web page’s code. We needed a way to provide the web part’s URL to the page at run time and dynamically load and render the web part. Here is how we solved it.

The first step is knowing how to virtually load a web part to a page at run time. A web part is just a type of web control. A control can be virtually loaded to a page (or any control that has a method to add a child control to it) using the Add method. Example: Page.Controls.Add(Control control). The first problem is how do you instantiate a control object at run time if you don’t know which control you’ll need at design time. The class System.Web.UI.TemplateControl contains a method called LoadControl(string virtualPath). This method returns a System.Web.UI.Control object. The control object can then be loaded on the page using the Add method.

Since the virtualPath parameter of the LoadControl method is a string, you don’t need to write the “new” statement to create the Control object. The LoadControl method does that for you. So, now the only problem is how to get the virtual path of the control. Our solution was to place all dynamically loaded web parts into the same directory of the web site. We added a configuration to the web.config that provides the path to this folder. With this in place, it’s only a matter of determining which web part the user has selected and map that to the web parts filename. This can be done in many different ways depending on the how the particular web site functions. Once you have the filename, concatenate it to the control folder path and pass the string to LoadControl.

The included code demonstrates the use of the objects mentioned above. It is not intended to compile and run as written.

 using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class MyWeb : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {}

    protected void SelectedNodeChanged(object sender, TreeNodeEventArgs e)
    {
        try
        {
            //The user selects an item out of a tree view control.  The item (array[0]) is 
            //passed to a static method that returns the web control's filename.
            TreeNode selectedNode = e.Node;
            if (selectedNode != null)
            {
                string[] array = selectedNode.Value.Split(',');
                if (array.Length == 2)
                {
                    //These next three statements demonstrate how to load a web control dynamically.
                    //Get the path the control folder.
                    string urlPath = ConfigurationManager.AppSettings["ControlFolderPath"];

                    //Create the virtual path string.
                    string virtualPath = string.Format("{0}/{1}", urlPath, MyStaticUtil.GetControlName(array[0]));

                    //Load the control into the page.  It's more likely that you would load the control into a panel.
                    Page.Controls.Add(LoadControl(virtualPath));
                }
            }
        }
    }
}