How to add user control dynamically into another usercontrol-ASP.NET

You might face situations where you have to add the user controls to your page dynamically. Based on some criteria, you will decide during runtime whether to load a user control or not. For this purpose, there are methods like LoadControl and Controls. Add.

The LoadControl method is used to load control to the page, and this is done in the Page_Load event of the page in which it is loaded. The user control name is given an argument to the LoadControl method to load that user control.

The Controls.Add method is used to place the user control on the page. But merely using this method will place it on your page but not sure where it will place. So you need a placeholder to add this control. For example, consider the code given below,


With the above syntax, you can add a user control to any placeholder. You can also use panel control which can hold the user control. Thus you can add a user control dynamically to the web page.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uc1.ascx.cs" Inherits="uc1" %>  
<asp:Label runat="server" text="uc1" ID="Label1" />  
<asp:Panel runat="server" id="p1" >Panel UC1</asp:Panel> 


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uc2.ascx.cs" Inherits="uc2" %>  
<br><asp:Label runat="server" text="uc2" ID="Label1" /> 


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoadUserControl.aspx.cs"  
Inherits="LoadUserControl" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
<html xmlns="" >  
<head runat="server">  
  <title>Untitled Page</title>  
  <form id="form1" runat="server">  
using System;  
using System.Data;  
using System.Configuration;  
using System.Collections;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  

public partial class LoadUserControl : System.Web.UI.Page  
protected void Page_Load(object sender, EventArgs e)  
    UserControl uc1 = (UserControl)LoadControl("uc1.ascx");  
    Control uc2 = uc1.LoadControl("uc2.ascx");  
    Control p1 = uc1.FindControl("p1");  
Next Post Previous Post
No Comment
Add Comment
comment url