Hello Friends,
Here I will explain you how can you load dynamically user control and perform delegate event on it.
Let's see example here.
Usercontrol : Calc.ascx
-------------------------------
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Calc.ascx.cs" Inherits="Calc" %>
<asp:Label ID="lblNum1" runat="server" Text="Enter The Number One"></asp:Label>
<asp:TextBox ID="txtNum1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblOperation" runat="server" Text="+" runat="server"></asp:Label><br />
<asp:Label ID="lblNum2" runat="server" Text="Enter The Number Two"></asp:Label>
<asp:TextBox ID="txtNum2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnAnswer" runat="server" Text="Answer" CausesValidation="false" OnClick="btnAnswer_Click" />
<br />
Usercontrol : Calc.ascx.cs
--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Calc : System.Web.UI.UserControl
{
public delegate void PerformOperationHandler(double num1, double num2);
public event PerformOperationHandler PerformOperation;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAnswer_Click(object sender, EventArgs e)
{
if (PerformOperation != null)
{
PerformOperation(double.Parse(txtNum1.Text),double.Parse(txtNum2.Text));
}
}
}
Page Name:Default.aspx
--------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<%@ Reference Control="~/Calc.ascx" %>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="placeholder" runat="server"></asp:PlaceHolder>
<br />
<asp:Label ID="lblAnswer" runat="server"></asp:Label>
</div>
</form>
Page Name:Default.aspx.cs
----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControl Calculation = LoadControl("~/Calc.ascx") as UserControl ;
placeholder.Controls.Clear();
placeholder.Controls.Add(Calculation);
((Calc)Calculation).PerformOperation+=new Calc.PerformOperationHandler(PerformOperation);
}
public void PerformOperation(double num1, double num2)
{
lblAnswer.Text = (num1 + num2).ToString();
}
}
I hopes it will help you.
Regards,
Kinjal Shah
Send Push Notification using C#
5 years ago