delegates events in c#

Create delegates events in c sharp


Whate is delegate ?

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

delegates events in control

Delegates and Events are two very powerful features of .NET. Events are the cornerstone of GUI programming and Delegates are used in implementing them.

There are three steps in defining and using delegates:
  • Declaration
  • Instantiation and
  • Invocation


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="SampleControl.ascx" TagName="SampleControl" TagPrefix="uc1" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:SampleControl ID="SampleControl1" runat="server" />
    </div>
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Width="300px" OnTextChanged="TextBox1_TextChanged" AutoPostBack=true></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" Width="300px"></asp:TextBox>
    </div>
    </form>
</body>
</html>


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)
    {
        SampleControl1.textIsChanged += this.test;
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        TextBox2.Text = "New value of text is --->>> " + TextBox1.Text;
    }

    protected void test(string mytest)
    {
        TextBox1.Text = mytest;
        TextBox2.Text = "New value of text is --->>> " + TextBox1.Text;
    }

}

SampleControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SampleControl.ascx.cs" Inherits="SampleControl" %>
<asp:Button ID="Button1" runat="server" Text="Button" Width="173px" OnClick="Button1_Click" />

SampleControl.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 SampleControl : System.Web.UI.UserControl
{
    public delegate void myTextChanged(string text);
    public event myTextChanged textIsChanged;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void Button1_Click(object sender, EventArgs e)
    {
        textIsChanged("Sample value from control");
    }
}

Source Code : Download
delegates events in c# delegates events in c# Reviewed by Bhaumik Patel on 7:39 PM Rating: 5