Click here to Skip to main content
15,880,891 members
Articles / Programming Languages / Visual Basic
Article

Step by Step: Event handling in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.63/5 (49 votes)
22 Sep 2003Public Domain2 min read 444.8K   114   14
Step by step guide to implement event handling in VB.NET.

Introduction

In this step by step article, we look at implementing event handling in VB.NET.

Implementing events

  • Step 1 - Create an EventArgs class

    If you need to pass arguments to the event handler, a specific EventArgs class has to be made. Eventually, a suitable EventArgs class might already be available, but in most cases, you will have to create one to tailor your specific arguments.

    If you do not need to pass arguments to the event handler (except the sender), then no subclass of EventArgs is needed. However, note that you should still define the event method with an argument of type System.EventArgs, and then pass System.EventArgs.Empty.

    Create the EventArgs as follows:

    VB
    Public Class StartEventArgs
        Inherits System.EventArgs
    
        'Provide one or more constructors, as well as fields and
        'accessors for the arguments.
    
    End Class

    Note: All EventArgs classes should have a name ending by EventArgs.

  • Step 2 - Create an event

    For each kind of event, an Event is created in the sending class:

    VB
    Public Class Sender
    
        Public Event Start(ByVal sender As Object, _ 
                 ByVal e As StartEventArgs)
    
        '...
    
    End Class

    Note: In VB.NET no explicit declaration of the delegate class is needed.

  • Step 3 - Create OnEvent methods

    Although not required, it is a good practice to create protected overridable OnEvent methods for your events:

    VB
    Protected Overridable Sub OnStart(ByVal e As StartEventArgs)
        RaiseEvent Start(Me, e)
    End Sub

    You can now call this method whenever you want to send the Start event. i.e.:

    VB
    OnStart(New StartEventArgs(data))
  • Step 4 - Make the event default

    When your class represents a component, it is a good practice to make the most commonly used event, the default event. Add a DefaultEvent attribute in front of your sender class:

    VB
    <System.ComponentModel.DefaultEvent("Start")> _
        Public Class Sender
        
        Inherits System.ComponentModel.Component
        '...

Handling events (static)

Under handling events statically, we understand having a WithEvents field to the sender.

Any field pointing to an object that can send events, can have the WithEvents modifier, in which case you can easily write event handlers by creating subroutines with the same signature as the event, and marked as Handles <sender>.<event>. The name of the method is of no matter, but by default, VS.NET uses <fieldname>_<event>:

VB
Public Class Receiver

    Friend WithEvents MySender As Sender

    Private Sub MySender_Start(ByVal sender As Object, _
         ByVal e As StartEventArgs) Handles MySender.Start
    
        '...
    End Sub

End Class

Handling events (dynamic)

When you have no field to the event sending object, i.e. because the object is passed as parameter to a method that can be called an unspecified number of times, then you can dynamically register to the event using the AddHandler operation:

VB
AddHandler sender.Start, AddressOf Me.HandleStart

To remove the handler, use the RemoveHandler operation:

VB
RemoveHandler sender.Start, AddressOf Me.HandleStart

The handling method is a regular subroutine with the same signature as the event (no Handles is needed):

VB
Public Sub HandleStart(ByVal sender As Object, _
           ByVal e As System.EventArgs)
    '...
End Sub

Code sample

VB
Public Class StartEventArgs
    Inherits System.EventArgs

    'Provide one or more constructors, as well as fields and
    'accessors for the arguments.

End Class

Public Class Sender

    Public Event Start(ByVal sender As Object, ByVal e As StartEventArgs)

    Protected Overridable Sub OnStart(ByVal e As StartEventArgs)
        RaiseEvent Start(Me, e)
    End Sub

    '...

End Class

Public Class Receiver

    Friend WithEvents MySender As Sender

    Private Sub MySender_Start(ByVal sender As Object, _
          ByVal e As StartEventArgs) Handles MySender.Start
        '...
    End Sub

End Class

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Architect AREBIS
Belgium Belgium
Senior Software Architect and independent consultant.

Comments and Discussions

 
QuestionSuperbly simple and concise. Now, One question... Pin
b-k-w12-Sep-16 2:35
b-k-w12-Sep-16 2:35 
AnswerRe: Superbly simple and concise. Now, One question... Pin
b-k-w12-Sep-16 2:42
b-k-w12-Sep-16 2:42 
QuestionVb Pin
Member 123143168-Feb-16 5:09
Member 123143168-Feb-16 5:09 
AnswerRe: Vb Pin
Rudi Breedenraedt8-Feb-16 23:34
Rudi Breedenraedt8-Feb-16 23:34 
GeneralMy vote of 5 Pin
Alwafi22027-Nov-14 12:59
Alwafi22027-Nov-14 12:59 
GeneralMy vote of 5 Pin
GuyThiebaut18-Jul-13 2:10
professionalGuyThiebaut18-Jul-13 2:10 
GeneralRe: My vote of 5 Pin
Rudi Breedenraedt18-Jul-13 4:58
Rudi Breedenraedt18-Jul-13 4:58 
GeneralMy vote of 3 Pin
User 91786121-Oct-12 22:18
User 91786121-Oct-12 22:18 
GeneralRe: My vote of 3 Pin
Rudi Breedenraedt1-Oct-12 22:55
Rudi Breedenraedt1-Oct-12 22:55 
GeneralRe: My vote of 3 Pin
User 91786121-Oct-12 23:00
User 91786121-Oct-12 23:00 
GeneralNice article Pin
Bhati_1_Vipin17-Sep-12 20:13
Bhati_1_Vipin17-Sep-12 20:13 
QuestionEvent Handling? Pin
salon19-Jan-07 0:47
salon19-Jan-07 0:47 
Questionevent handling in service Pin
tomsmaily12325-Aug-06 4:51
tomsmaily12325-Aug-06 4:51 
GeneralGood one for beginners Pin
noby_datasoft15-Apr-04 16:52
noby_datasoft15-Apr-04 16:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.