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:
- <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)
- {
-
- Control _dummyUserControl = (Control)Page.LoadControl("DummyControl.ascx");
-
-
- pnlDynamicControl.Controls.Add(_dummyUserControl);
- }
- }
That's it, we are done. Run the application and see the results:
Read more articles on C#: