Handles Keyword

   
Handles Keyword

Syntax

 Handles   name   .   event   
name (required; String literal)

The name of the class or object whose event the subroutine is handling

event (required; String literal)

The name of the event that the subroutine is handling

Description

Defines a procedure as the event handler for a particular event

Rules at a Glance

  • The Handler keyword is used to define event handlers for events trapped by an object defined with the WithEvents keyword.

  • The Handles keyword can only be used with a procedure declaration, since an event handler must be a procedure rather than a function.

  • The Handles keyword must be placed on the same line as, and at the end of, a procedure declaration.

Example

In a Windows application, the following definition appears in the declarations section of the Form1 class module:

 Public WithEvents Button1 As Button 

The Button1 object is then instantiated with a line of code like the following in the New subroutine or another initialization routine:

 Me.Button1 = New Button 

The Button1 object's Click event can then be handled with a event handler like the following:

 Private Sub Button1_Click(ByVal sender As System.Object, _                           ByVal e As System.EventArgs) _             Handles Button1.Click    MsgBox("Hello, World!") End Sub 

Programming Tips and Gotchas

  • The WithEvents and Handles are designed to define event handlers at compile time. If you want to define event handlers dynamically at runtime, use the AddHandler and RemoveHandler statements.

  • By convention, event handlers take the form objectname _ eventname . For example, the Click event of an object named Button1 could be trapped by an event handler named Button1_Click. Although this convention is highly recommended, it is not obligatory .

VB.NET/VB 6 Differences

The Handles keyword is new to VB.NET. In VB 6, the link between an object and its event handler was handled automatically and transparently by Visual Basic.

See Also

WithEvents Keyword

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net