In the example that follows, we declare a login dialog class that uses the button class. The dialog box class contains two buttons: Ok and Cancel buttons.
Program Listing 13-2:
public class Logindialog Form
{
Button okbutton;
Button CancelButton;
Public Logindialog () {
okbutton=new Button (...);
Okbutton.click+=new EventHandler (Okbuttonclick);
Cancelbutton=new Button (...);
Cnacelbutton.click+=new EventHandler (Cancelbuttonclick);
}
void Okbuttonclick (Object Sender,eventargs e) {
//Handle Okbutton.click event
}
void Cancelbuttonclick (object Sender,eventargs e) {
//handling Cancelbutton.click event
}
}
In the example, two instances of the button class were used, and the subscription of the event was implemented by adding the left operator "+ =" to the event:
Okbutton.click+=new EventHandler (Okbuttonclick);
This way, whenever an event is triggered, the method is invoked.
The undo of an event takes the left operator "=":
Okbutton.click-=new EventHandler (Okbuttonclick);
If an event is declared in a class, and we want to use the event in the same way as a domain, then the event cannot be abstract or contain an event access declaration explicitly. Once these two conditions are met, events can also be used in any field that can be used.
Note: The triggering of an event is equivalent to the prototype-delegate represented by the calling event, so calls to the delegate prototype must be checked to ensure that the delegate is not null.