
Handling Control Events | 111
ASP.NETServer
Controls
This is the Title of the Book, eMatter Edition
Copyright © 2008 O’Reilly & Associates, Inc. All rights reserved.
Note that the event handler changes slightly (EventArgs is replaced by the
CommandEventArgs subclass, which contains information about the clicked
command button):
' Visual Basic .NET
Sub Button_Command(sender As Object, ce As CommandEventArgs)
Select ce.CommandName
Case "Sort"
' Sort logic
Case "Filter"
' Filter logic
End Select
End Sub
//C#
void Button_Command(Object sender, CommandEventArgs ce)
{
switch(cs.CommandName)
{
case "Sort":
// Sort logic
case "Filter":
// Filter logic
}
}
It’s a good habit to name your event handlers based on the name of the control
whose event they handle and the name of the event, separated by an underscore
(e.g.,
MyBtn_Click). However, as you can see from the OnCommand event
example, you may want to make an exception sometimes.
Wiring Up Events Programmatically
Programmatic wiring of control events is typically used with code-behind classes;
it’s a little more complicated than the declarative technique, but still pretty
straightforward. Note that programmatic event wiring is language dependent.
Two techniques wire up events programmatically in Visual Basic .NET and one
wires up events in C#.
The preferred approach for programmatically wiring events in Visual Basic .NET
uses the
WithEvents and Handles keywords ...