Load User Control Dynamically Using C#

In this article we will learn how to load the user-control onto the page dynamically.

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 mark-up will look like the following: 
  1. <form id="form1" runat="server">  
  2.        <div>  
  3.            <asp:Panel ID="pnlDynamicControl" runat="server">  
  4.            </asp:Panel>  
  5.        </div>  
  6.    </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: 
  1. public partial class WebForm1 : System.Web.UI.Page  
  2.     {  
  3.         protected void Page_Load(object sender, EventArgs e)  
  4.         {   
  5.             //Load the control   
  6.             Control _dummyUserControl = (Control)Page.LoadControl("DummyControl.ascx");  
  7.   
  8.             // Add the control to the panel  
  9.             pnlDynamicControl.Controls.Add(_dummyUserControl);  
  10.         }  
  11.     }  
That's it, we are done. Run the application and see the results:

Read more articles on C#: