Event Handling in C# 2.0
-
Hi All, I am working on a project that requires handling of custom events. Some class will raise the DataEvent of RaiseEventClass. I have to implement event handler for the DataEvent in the RaiseEventClass. Please help me how to implement event handler. Please show some codes if possible. Below is the skeleton of the class. Thanks in advance! public class RaiseEventClass { public delegate void RaiseEventDelegate(ArrayList files); public event RaiseEventDelegate DataEvent; public void SearchFiles(ArrayList list) { DataEvent(list); //raising event for testing } }
A.Asif
-
Hi All, I am working on a project that requires handling of custom events. Some class will raise the DataEvent of RaiseEventClass. I have to implement event handler for the DataEvent in the RaiseEventClass. Please help me how to implement event handler. Please show some codes if possible. Below is the skeleton of the class. Thanks in advance! public class RaiseEventClass { public delegate void RaiseEventDelegate(ArrayList files); public event RaiseEventDelegate DataEvent; public void SearchFiles(ArrayList list) { DataEvent(list); //raising event for testing } }
A.Asif
First learn, then code :-) You could start here[^] or here at CP[^].
SkyWalker
-
Hi All, I am working on a project that requires handling of custom events. Some class will raise the DataEvent of RaiseEventClass. I have to implement event handler for the DataEvent in the RaiseEventClass. Please help me how to implement event handler. Please show some codes if possible. Below is the skeleton of the class. Thanks in advance! public class RaiseEventClass { public delegate void RaiseEventDelegate(ArrayList files); public event RaiseEventDelegate DataEvent; public void SearchFiles(ArrayList list) { DataEvent(list); //raising event for testing } }
A.Asif
First you should change
A.Asif wrote:
public void SearchFiles(ArrayList list) { DataEvent(list); //raising event for testing }
to
public void SearchFiles(ArrayList list) { if (DataEvent != null) DataEvent(list); //raising event for testing }
just to handle the case when no handler is attached to the event. Then if you've got an RaiseEventClass object (call it "myObj") and want to handle the event just usemyObj.DataEvent += new RaiseEventDelegate(myHandler )
where myHandler is a function likevoid myHandler(ArrayList files) { // TODO: whatever you want }
By the way: afert typing "+= new" in the line where you attach the event you can hit twice and VS will write a handler-function for you (so you don't have to check the delegate to know exactly what kind of parameter / return you have to use) One other comment: you should include a "sender" parameter in every event you write (like object sender, or RaseEventClass sender - this helps you handle events from many sources in the same handler function and is always a good pattern.