Defining methods for an Event Handler (Delegate)

by Jagadish Pulakhandam on 3/20/2012 8:31:37 PM
Rated 0 from 0 votes
Brief: Demonstrates 10 different ways on registering event handlers in various ways including delegates, anonymous methods, inline delegates, Action delegate, Lambda syntax etc.
Posted to: Events, Delegates and Lambda Expressions in .NET Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Following source code explains the following:
  • How to register for event handlers (or handle events) using traditional/classic syntax
  • How to define a custom delegate, assign a method and register the same for event handler (to handle an event)
  • How to define a custom delegate, assign an anonymous method and handle an event (using event handler)
  • How to create an instance of an Event Handler delegate using anonymous method
  • How to use anonymous method (with and without parameters) to register for an Event Handler (inline delegate)
  • How to create an instance of Action delegate using anonymous method and get it registered as Event Handler
  • How to use lambda syntax based anonymous methods with Action delegates (and finally register for Event Handlers)
  • How to use lambda syntax based anonymous methods to register for Event Handlers.

Screen shot:



Source code:

01.using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Linq;
07.using System.Text;
08.using System.Windows.Forms;
09.using System.Collections.ObjectModel;
10. 
11.namespace WindowsFormsApplication1
12.{
13.    public partial class Form1 : Form
14.    {
15.        BindingList<Employee> lstEmployees = new BindingList<Employee>();
16. 
17.        public Form1()
18.        {
19.            InitializeComponent();
20.        }
21. 
22.        private void btnAdd_Click(object sender, EventArgs e)
23.        {
24.            lstEmployees.Add(new Employee()
25.            {
26.                Empno = int.Parse(txtEmpno.Text),
27.                Ename = txtName.Text,
28.                Sal = int.Parse(txtSal.Text)
29.            });
30.        }
31. 
32.        //Classic way of registering event handlers
33.        //------------------------------------------
34.        private void Form1_Load(object sender, EventArgs e)
35.        {
36.            listBox1.ValueMember = "Empno";
37.            listBox1.DisplayMember = "Ename";
38.            listBox1.DataSource = lstEmployees;
39. 
40.            lstEmployees.ListChanged += new ListChangedEventHandler(lstEmployees_ListChanged);
41.        }
42. 
43.        void lstEmployees_ListChanged(object sender, ListChangedEventArgs e)
44.        {
45.            lblEmpCount.Text = lstEmployees.Count.ToString();
46.        }
47. 
48.    }
49. 
50.    public class Employee
51.    {
52.        public int Empno { get; set; }
53.        public string Ename { get; set; }
54.        public int Sal { get; set; }
55.    }
56. 
57.}

Way 2:

//delegate pointing to an existing method
//----------------------------------------
delegate void ListChanged(object lst, ListChangedEventArgs args);
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
 
    ListChanged lstchanged = lstEmployees_ListChanged; //this is shortcut to using "new ListChanged(methodName)"
 
    lstEmployees.ListChanged += new ListChangedEventHandler(lstchanged);
}
void lstEmployees_ListChanged(object sender, ListChangedEventArgs e)
{
    lblEmpCount.Text = lstEmployees.Count.ToString();
}

Way 3:

//delegate pointing to an anonymous method
//-------------------------------------------------
delegate void ListChanged(object lst, ListChangedEventArgs args);
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
 
    ListChanged lstchanged = delegate(object lst, ListChangedEventArgs args)
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
 
    lstEmployees.ListChanged += new ListChangedEventHandler(lstchanged);
}

Way 4:

//assigning anonymous method through a delegate variable of same type
//-------------------------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
 
    ListChangedEventHandler ListChanged = delegate(object lst, ListChangedEventArgs args)
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
 
    lstEmployees.ListChanged += ListChanged;
}

Way 5:

//assigning anonymous method directly (with params) also called inline delegate
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
 
    lstEmployees.ListChanged += delegate(object lst, ListChangedEventArgs args)
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
}

Way 6:

//Anonymous method with no parameters
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
 
    lstEmployees.ListChanged += delegate
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
}

Way 7:

//Anonymous method with Action delegate (we need not declare our own delegate)
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
    Action<object, ListChangedEventArgs> oAction = delegate
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
 
    lstEmployees.ListChanged += new ListChangedEventHandler(oAction);
}

Way 8:

//Anonymous method with Action delegate lambda syntax (good for multiple lines)
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
    Action<object, ListChangedEventArgs> oAction = (o, args) =>
    {
        lblEmpCount.Text = lstEmployees.Count.ToString();
    };
 
    lstEmployees.ListChanged += new ListChangedEventHandler(oAction);
}

Way 9:

//Anonymous method with Action delegate lambda syntax (valid if one line)
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
    Action<object, ListChangedEventArgs> oAction = (o, args) => lblEmpCount.Text = lstEmployees.Count.ToString();
    lstEmployees.ListChanged += new ListChangedEventHandler(oAction);
}

Way 10:

//Inline delegate lambda syntax (valid if one line)
//-----------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
    listBox1.ValueMember = "Empno";
    listBox1.DisplayMember = "Ename";
    listBox1.DataSource = lstEmployees;
    lstEmployees.ListChanged += (o, args) => lblEmpCount.Text = lstEmployees.Count.ToString();
}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following