Load User Control Dynamically Using C#

Introduction

In this article, we will try to learn how we can load a user control dynamically using C#. So, let's start by adding an .aspx page and a user control on our page. We name this control as DummyControl.ascx. On the main page, we will add an ASP panel, say pnlDynamicControl. So, our page markup will look like the following. 

<form id="form1" runat="server">  
       <div>  
           <asp:Panel ID="pnlDynamicControl" runat="server">  
           </asp:Panel>  
       </div>  
   </form>  

Next, add some dummy text on the user control. Now, let's move into the code-behind of the page and write the code to load the user control into the panel. We will do this by using the LoadControl method of the Page class. This method expects a parameter, which is the url of the user-control inside the project. So, our code will look like the following. 

public partial class WebForm1 : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {   
            //Load the control   
            Control _dummyUserControl = (Control)Page.LoadControl("DummyControl.ascx");  
  
            // Add the control to the panel  
            pnlDynamicControl.Controls.Add(_dummyUserControl);  
        }  
    }  

That's it, we are done. Run the application and see the results.

usercontrol

Read more articles on C#


Similar Articles