In C #, "Event" is a method in which the class can notify customers of objects that meet certain conditions and certain events occur. When an event is used, the object that owns the event does not have to know who needs to be notified. Once a condition is met, the event will be automatically called to correctly notify each object to be notified. By using events, the modularization of the program is improved.
To use custom events in a program, follow these steps:
1. Declare the event
To declare an event in the class, you must first declare the delegate type of the event:
Public delegate void SelectionChangedEventHandler (object sender,
SelectionChangedEventArgs e );
Note: Because the sample program needs to pass data in the event, the SelectionChangedEventArgs derived class of EventArgs is defined.
Public class SelectionChangedEventArgs: EventArgs
{
Private string m_selection;
// This attribute is used to pass event data
Public string Selection
{
Get {return m_selection ;}
}
Public SelectionChangedEventArgs (string selection)
{
M_selection = selection;
}
}
The delegate type defines a set of parameters passed to the method for processing the event. Multiple events can share the same delegate type. Therefore, this step is required only when no suitable delegate type is declared.
Next, declare the event itself:
Public event SelectionChangedEventHandler SelectionChanged;
2. Call events
If no customer associates the delegate with this event, this field is blank; otherwise, this field references the delegate that should be called when the event is called. Therefore, when calling an event, you must first check whether it is empty and then call the event.
Public class Form2: System. Windows. Forms. Form
{
......
Public event SelectionChangedEventHandler SelectionChanged;
......
Private void combobox#selectedindexchanged (object sender, System. EventArgs e)