C# Event Handling

Well, this is my first post on this blog, so I figured I would go with something a little on the basic side, but something I had a lot of trouble dealing with when I started out programming.  Creating and using events in C#.

So, lets say that your  trying to use a progress bar on a form to report the status of some long running task taking place in a separate class file you have.  The first thing you need to do is create a method delegate in your class file. Then, we’ll need to create the event itself, also in the class file.

public delegate void progressUpdateDel(int min, int max, int current);
public event progressUpdateDel progressUpdate;

The delegate defines how the method that receives the event has to be formed, and what variables will be coming across.  The event declaration simply says that there is an event, and it will be in the progressUpdateDel format.

The next step is going to be to subscribe your form to the class.  You’ll be doing this the same way that you would subscribe to a button’s onClick event.

WorkerClass myClass = new WorkerClass();
myClass.progressUpdate += new myClass.progressUpdateDel(myClass_progressUpdate);

In Visual Studio, after you type out myClass.progressUpdate you can hit tab twice to have everything including the += auto-inserted, and it will also write out a corresponding method for you.  Kinda handy : -).  Here’s what the function should look like in your form class.

private void myClass_progressUpdate(int min, int max, int current)
{
     this.progressBar1.min = min;
     this.progressBar1.max = max;
     this.progressBar1.value = current;
}

And finally all thats left is actually calling the event from your worker class. When the event is called, it automagically activates any methods that have subscribed to it. Pretty nifty, and can be used for, well, just about anything.

...
if(this.progressUpdate != null)
     progressUpdate(0, myMax, myCurrent);
...

Thats it!  Nothin more to it than that.  The if line when your calling progressUpdate is very important.  Calling the event will cause an exception if there are no other classes subscribed to its event, so don’t forget that line!

  1. No comments yet.

  1. No trackbacks yet.