When defining methods to handle events, there are basically two things you must know:
- the name or names of the events supported by the control, and
- the appropriate event-handling signature for the event you need to handle.
For example, the method to handle a Button control's Click event must have a signature similar to the following.
protected void methodName ( object src, EventArgs e )
Private Sub methodName ( ByVal src As Object, ByVal e as EventArgs ) |
|
C# |
VB |
IMPORTANT: Event-handling methods can have any name, but must have a signature that corresponds to the appropriate event-handler delegate signature. Otherwise, a compile-time error is thrown.
The following examples demonstrate how you can specify and code a handler for the Click event of a Button control.
The method signature depends on the type of the event object passed to the handler, which in turn depends on the control for which you are creating the event handler.
For example, the method to handle a Button control's Command event must have a signature similar to the following.
protected void methodName ( object src, CommandEventArgs e )
Private Sub methodName ( ByVal src As Object, ByVal e as CommandEventArgs ) |
|
C# |
VB |
The following example demonstrates how you can specify and code a handler for the Command event of a Button control.
For information on specific event arguments, see the reference documentation for the control event you are working with.
When you already have an event handler with the appropriate signature, you can then bind the control event to it. There are basically two ways to attach handlers to events, declaratively at design time or programmatically at run time.
The following example demonstrates how you can programmatically specify a common handler for the Command events of a Button control set.
// set common button properties
foreach ( Control c in header [ 1 ].Controls ) {
( ( Button ) c ) .Font.Bold = true;
( ( Button ) c ) .BackColor = System.Drawing.Color.DarkRed;
( ( Button ) c ) .ForeColor = System.Drawing.Color.Khaki;
( ( Button ) c ) .Command += new CommandEventHandler ( setPageCustom );
}
' set common button properties
Dim c As Control
For Each c In header ( 1 ) .Controls
CType ( c, Button ) .Font.Bold = True
CType ( c, Button ) .BackColor = System.Drawing.Color.DarkRed
CType ( c, Button ) .ForeColor = System.Drawing.Color.Khaki
AddHandler CType ( c, Button ) .Command, AddressOf setPageCustom
Next c |
|
C# |
VB |