What is an event handler and explain how it is designed ?

 

About Event Handler

Events are declared using delegates.

Events are the higher level of Encapsulation over delegate.

A delegate that exists in support of an event is called as an event handler.

Event handlers are methods in an object that are executed in response to some events occurring in the application.

Syntax of an Event Handler using delegate:

 
Line 1: public delegate void MyDelegateEventHandler(object sender, MyEventArgs e);
Line 2: public event MyDelegateEventHandler objEventHandler;

Let's illustrate of Line 1 syntax.

Public : An access modifier which states that delegate object can use outside of a class.
Delegate : Keyword used to declare the custom delegate.
Void : Event Handler return void means it does not return any value. If we specify other than the void like (string, int, double) then it should return any value of that type.
Input parameters for an even handler are Object and EventArgs.
The first input parameter is an Object that raises the event.
The second parameter is EventArgs that contains information about the Event.

Let's illustrate of Line 2 syntax.

Public : An access modifier which states that event can be use outside of a class.
Event : Keyword used to declare the custom event.
MyDelegateEventHandler : This is the custom delegate type which is defined in Line 1.Followed by Event name ("objEventHandler").

Understanding Delegates

To understand how to design and use a delegate in c-sharp visit here

Understanding Event Handler using an Example

I hope that you have understood the delegates now let's go back to event handlers.

So now for better understanding on event handler let take up a simple and a popular example i.e. Publisher and Subscriber means if a publisher every time publish or do anything then subscriber who has subscribed to that publisher will get notification.

So let's take up a simple windows form application where we have created a search form as shown below.

Let's treat this above form as our publisher.In the next step we will create our subscribers or create our notifications. We have created two error notifications i.e. XML Error notification and CSV Error notification in two separate windows form application as shown below.

XMLErrorNotification Form

CSVErrorNotification Form

Above the example which demonstrates on error logging mechanism in two different formats i.e. xml and csv format. If any error occurred in our search form then it will automatically notify error in two ways i.e. xml and csv.

Step 1

Create delegate method in our search form as shown below.

 
public delegate void MyDelegateLogError(object sender, LogErrorEventArgs e);

 

So MyDelegateLogError is our event handler with :

The first input parameter is an Object that raises the event.

The second parameter is custom LogErrorEventArgs which is derived from EventArgs that contains information about the Event.

Designing Custom Event Handler Mechanism

For GUI (Graphic user interface) events, you can use objects of these specialized EventArgs classes without creating your own specialized EventArgs classes. However, for non GUI event, you need to create your own specialized EventArgs class as shown below.

 
 public class LogErrorEventArgs : EventArgs{
        public string ErrorMsg = "";
 }

Step 2

Using our delegate object let’s create event. Here we need to create two events

  1. For XML Error Log
  2. For CSV Error Log

The delegate object is referenced using the keyword event as shown below.

Note: Events are the higher level of Encapsulation over delegate.

 
public event MyDelegateLogError EventCSVLogError;
public event MyDelegateLogError EventXMLLogError;

Now that we have created the two events we need to use it in our two different forms which we have created for xml and csv.

Step 3

First let's add our event code in csv form.

As we know delegate object referenced only with a signature that exactly matches the method signature that we are trying to encapsulate. So for our delegate object we need to create custom method in csv form that will match exactly with our delegate object.

 
public void CSVLog(object sender, LogErrorEventArgs e)
{
 …..
}

Above we have created a custom method "CSVLOG" which matches exactly with delegate object. Method logs or writes any error in csv format.

Now let's point this method "CSVLOG" to our event "EventCSVLogError" as shown below.

 
public Form1 obj;
private void CSVSubscriber_Load(object sender, EventArgs e)
{
            obj.EventCSVLogError += CSVLog;
}

We have pointed our custom "CSVLOG" method to an event in CSV form load "obj" is an object of our search form because we have created public events in search form.

Same way we can repeat the process for xml log too.

Note: For writing anything to csv format or xml format we need to use below namespace and to use custom "LogErrorEventArgs" you need to reference it.

using System.IO;
using System.Xml;

Step 3

To assign the custom error message in our search form we will use our "LogErrorEventArgs" object since we are logging error in two different formats so we have to create two objects as shown it below.

 
LogErrorEventArgs e1 = new LogErrorEventArgs();
LogErrorEventArgs e2 = new LogErrorEventArgs();

"e1" and "e2" are the objects of "LogErrorEventArgs" which we have created in our search form "Form1".

Step 4

Let's create custom two methods (xml, csv) of fire event as shown below.

 
public void FireEvenForCSV(LogErrorEventArgs e){
            if (EventCSVLogError != null)
            {
                EventCSVLogError(this, e);
            }
}
public void FireEvenForXML(LogErrorEventArgs e){
            if (EventXMLLogError != null)
            {
                EventXMLLogError(this, e);
            }
}

Above methods which will check if it not null then it will fire up event. In simple words it will call the "CSVLOG" and "XMLLOG" methods respectively.

Step 5

Let's experiment our example to do that we will create some error in our search form button click and assign error message using two objects (e1, e2) of "LogErrorEventArgs" and finally fire events as shown below.

 
private void Search_Click(object sender, EventArgs e){
 try{
StreamReader strread = new StreamReader(@"E:\\BSCMSCIT\\OCT2010\\Practical5b-EventHandler\\datafiles.txt");
 }
 catch(Exception ex){
                label2.Text = "Problem in Reading Data File";
                e1.ErrorMsg = ex.Message.ToString();
                e2.ErrorMsg = ex.Message.ToString();
                FireEvenForCSV(e1);
                FireEvenForXML(e2);
  }
}

Above the code we have created some error in try block i.e. trying to read the file which is not available and catch exception or error message in catch block.

We wrote exception message to two objects (e1, e2) of "LogErrorEventArgs" and finally called fire events.

Displaying Event Handler Output.

So this is all about creating and using an event handler with delegate. If you friends have any query regarding this topic kindly let me know through your comments. If you like this article kindly share it with your friends. Thank you

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Jul
20
2013

Is C# is Modern, Type Safe, Versionable and Inter operability Language ?

CLICK TO READ FULL ARTICLE

Views - 9916 |Category - C#

Jul
09
2013

Discuss Boxing and Unboxing in the context of value types and reference types

CLICK TO READ FULL ARTICLE

Views - 7401 |Category - C#

Jul
07
2013

Understanding Switch Statement with the help of an example

CLICK TO READ FULL ARTICLE

Views - 5141 |Category - C#

Jul
07
2013

Checked and Unchecked operators using an example

CLICK TO READ FULL ARTICLE

Views - 5843 |Category - C#

Jul
07
2013

What is an Indexer? Explain how it is different from property in terms of implementation.

CLICK TO READ FULL ARTICLE

Views - 8004 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

rva8v