JG Vimalan's Blog

It is all about coding!

Creating custom events in C#

Mostly in Winforms application, we may need custom events.

By using custom events, we can perform specific action whenever need in the application. 

To create a custom events, follow these steps. 

Let us assume you have 2 classes, a.cs and b.cs. 

a.cs has a method say Display() which needs to be invoked by raising an user defined event from b.cs. 

Create event, delegate and raise them where ever necessay as shown in class b.cs 

class b{ 

  public Delegate void DelegateMyEvent;

  public event DelegateMyEvent MyEvent; 

  …

  …   

     If (MyEvent != null) //Check for null before raising it.

          MyEvent();

  …. 

Create a method in a.cs and attach it the event declared in class b.cs as follows: 

class a{

    private b obj = null; 

    //constructor

    public a ()    {

          obj = new b();

          obj.MyEvent += new DelegateMyEvent(Display); //Handle the event.

     } 

     private void Display()     {

          MessageBox.Show(“Working with custom events!!!”);

      }

So, whenever the needed in class b, raise the custom event and the Display() method in class a is invoked. This custom event is very useful when a complex winforms application is created.

Advertisements

October 9, 2009 - Posted by | C#.NET

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: