Use single UserControl multiple times in ASP.Net Page dynamically
Step 1: Lets create our Solution
Step 2: In UCHome.ascx
Step 3: In UCHome.ascx.cs
Step 5: In Home.ascx.cs
Step 1: Lets create our Solution
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCHome.ascx.cs" Inherits="UsingUserControlMultipleTimes.UCHome" %>
<div style="page-break-after:always">
<asp:Label ID="lblName" Font-Bold="true" runat="server"></asp:Label>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UsingUserControlMultipleTimes
{
public partial class UCHome : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void UserName(string Name)
{
lblName.Text = Name;
}
}
}
Step 4: In Home.ascx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="UsingUserControlMultipleTimes.Home" %>
<%@ Register TagPrefix="HomePage" TagName="header" Src="UCHome.ascx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UsingUserControlMultipleTimes
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
UCHome myControl = (UCHome)LoadControl("UCHome.ascx");
myControl.ID = "UCHome" +
i.ToString();
myControl.UserName("Testing " +
i.ToString());
myControl.Visible = true;
this.form1.Controls.Add(myControl);
}
}
}
}
Step 6: Run the Application
0 comments:
Post a Comment