Click here to Skip to main content
12,821,315 members (31,157 online)
Click here to Skip to main content
Add your own
alternative version


18 bookmarked
Posted 5 Nov 2008

event and custom eventargs in depth for beginners

, 12 Nov 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
learn how to attach event with an object and how to create custom eventargs for beginners


This article helps the beginners to understand how to define events and how to create custom EventRrgs to pass event specific data that may be required somewhere.


This article is for the beginners to actually understand the concept of event and how to apply it.

Before starting this article i would suggest to go through a quick definition and understanding of events and delegates:

Using the code

Download the article and save it in the hard disk. Then open the existing project using Visual Studio 2005. Go to File->Open->Web Site

What is Event?

Defintion 1:An event in c# is a specific delegate type variable.
Defintion 2:A event is a notification saying something has happened in the system.

So what we have got from these definitions?

It is very clear from the first definition is that before declaring an event we must declare a delegate as an event is a delegate type variable.From the second defintion it is very clear that the events get fired only when something interesting happens within the system.

What are interseting things?

Interest things can be anything.As we all know button click ,checkbox check, dropdown list selection change are events. Same way, we can define our own events.Adding an item to an arraylist(we can say it as arraylist_added event).

Example Description

I have a ArryList object and i want that whenever we add an item to the list it should publish(the object that triggers or throws or fires an event is called publisher class and who subscribes is known as Subscriber class--aka. Publisher-Subscriber Model) an event and the event will be subscribed by a Subscriber class that defines the EventHandler. Note: When a publisher class object fires an event that event can be subscribed by any number of Subscriber classes .

The System.Collections.ArrayList clas does not fire any event while adding new item into the list.So how can we throw an event while adding?

So, this is the question that you guys have got now. Right??? Simple man.........let that arraylist be as it is. We will just create our custom arraylist class and we will just override the Add method,

public virtual int Add(object value); 

This is the signature of the ArrayList Add method. So we will override this virtual method.

But How?

So the publisher class or the custom arraylist class looks like

public delegate void ArrayListItemAddEventHandler(object sender); 
public class MyArrayList:ArrayList 
	    public event ArrayListItemAddEventHandler added; 
	    public override int Add(object value) 
                 if (added != null) added(this); 
	        return base.Add(value); 

What we have done here?

As i already mentioned we have just overrided the Add method. Before calling the base class's Add method we fired the event. We have defined a delegate and the event should be the delegate type. Now the CustomArrayList will fire the event whenever we try to add anything in the list. That is for sure.

What Next?

Now we need to design the subscriber class that will subscribe the event and will do something usefull when notified. So it is clear that the subscriber class must have a EventHandler(just a function or method that matches the delegate signature) .

public class SubscriberClass
        public void AddedEventHandler(object sender)
            MessageBox.Show("An item has been added to the List");

So this is the subscriber class.Now we can write a main method that will show how to actually subscribe the notification.

static void Main(string[] args)
            MyArrayList list = new MyArrayList();
            SubscriberClass sc = new SubscriberClass();
            //so the subscriber class subscribes the event here
            list.added += new ArrayListItemAddEventHandler(sc.AddedEventHandler);
            //now adding something into the Custom Arraylist

As soon as the item will be added into the CustomArrayList it will fire the "added" event. As the Subscriber class has already subscribed the event so the EventHandler will be called and a messagebox will show "An item has been added" message. Now i think this much is clear for all. Now , suppose we also want to show some more information in the messagebox, say which number we have added.

What to do for that?As we know that EventArgs e is not going to give us information about teh added item in the list.

The sollution is we can inherit from EventArgs class and create our own EventArgs Class, say ArrayListItemAddEventArgs.

How does it look like?

public class ArrayListItemAddEventArgs : EventArgs
       public int addedItem;//this will keep track of currently added item to the list
       public ArrayListItemAddEventArgs(int item)
           addedItem = item;

fare enough

We also have to change the delegate singature as well as the EventHandler definition according to the change in delegate signature.

public delegate void ArrayListItemAddEventHandler(object sender,ArrayListItemAddEventArgs e); 

So we have to just add a single line of code to the add method.

ArrayListItemAddEventArgs e = new ArrayListItemAddEventArgs((int)value); 

So the custom arrylist class will look like

public delegate void ArrayListItemAddEventHandler(object sender,ArrayListItemAddEventArgs e);
   public class MyArrayList:ArrayList
       public event ArrayListItemAddEventHandler added;

       public override int Add(object value)
           ArrayListItemAddEventArgs e = new ArrayListItemAddEventArgs((int)value);
           if (added != null) added(this,e);
           return base.Add(value);

The Subscriber class

public class SubscriberClass
      public void AddedEventHandler(object sender,ArrayListItemAddEventArgs e)
          MessageBox.Show(string.Format("The item  {0} has been added to the List!", e.addedItem));

Now easily we can show the added item in the messagebox like this:

MessageBox.Show("An item has been added to the List"+e.addedItem);
So friends i think now you all got how to play with events.

How to hook an event handler in .net?

In case of .net the default delegate signature is

protected void Eventhandler(object sender,EventArgs e){}

Now, say we have a button control and we have another class that will subscribe the clicked event of that button.The class has its own eventhandler ButtonIsClicked defined into the class that matches the default delegate signature.

protected void ButtonIsClicked(object sender,EventArgs e){}

So in that case we have to add a single line of code.

button1.Clicked+=new System.Eventhandler(ButtonIsClicked);

So, when we click the button1 then Button_Clicked as well as ButtonIsClicked, both the methods will be called.

Note: Please vote this article according to your likings and for any types of confusion plz come back to me and post comments on it. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Joydeep Sen
Software Developer
India India
A dot net developer with 2.2 yrs of experience.
I am a MCP and MCTS in dot net 2.0 web application.
Have experience working with Microsoft Sydney, Australia.

You may also be interested in...


Comments and Discussions

GeneralNot very deep Pin
PIEBALDconsult6-Nov-08 16:35
memberPIEBALDconsult6-Nov-08 16:35 
GeneralRe: Not very deep Pin
Joydeep Sen9-Nov-08 19:12
memberJoydeep Sen9-Nov-08 19:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 13 Nov 2008
Article Copyright 2008 by Joydeep Sen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid