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,

PlaceHolder_Ctrl.Controls.Add(name_of_UserControl);

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.

uc1.ascx

<%@ 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> 

uc2.ascx

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

LoadControl.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoadUserControl.aspx.cs"  
Inherits="LoadUserControl" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
<html xmlns="http://www.w3.org/1999/xhtml" >  
<head runat="server">  
  <title>Untitled Page</title>  
</head>  
<body>  
  <form id="form1" runat="server">  
  <div>  
  
  </div>  
  </form>  
</body>  
</html>  
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");  
    Controls.Add(uc1);  
    Control uc2 = uc1.LoadControl("uc2.ascx");  
    Control p1 = uc1.FindControl("p1");  
    p1.Controls.Add(uc2);  
}  
}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم