A Review of VB Event Handling (WithEvents, AddHandler and AddressOf)

When you are building an application using VB, you will most certainly need to hook into various event sources.  While events are very common when you are constructing a GUI application (WPF, ASP.NET, Windows Forms), they are also very important for non-UI tasks such as working with threads, callbacks from database operations, and other tasks.

As it turns out, VB has a few "oddities" regarding how to hook into a given event, so I wanted to do a quick blog post which will hopefully clarify our choices.

First of all, when you are declaring a field of a Class, Structure or Module, you have the option of making use of the WithEvents keyword.  When you do so, you are able to selectively hook into events of interest using the Handles clause on a given class method. One part of this puzzle which is hidden from view is the fact that each and every .NET event is defined in termes of a related delegate.  As you may know, the .NET delegate type allows us to capture, in a strongly typed manner, the address of another method. Given this point, the method that uses the Handles clause must match the underlying delegate definition, or you will receive compile time errors!

Here is a simple example of capturing the Click event of the Windows Forms Button class.  Take note that the method receiving the event notification takes an Object as the first parameter, and a EventArgs as the second, given that the Click event has been defined in terms of a system delegate named System.EventHandler.

 Class MainWindow
 
Inherits Form

  ' Inform the Button we are interested in listening to
  ' events.
  Private WithEvents btnClickMe As Button

  Public
Sub New()
    btnClickMe =
New Button With {.Height = 100,
      .Width = 100, .Text =
"OK!"}
   
Me.Controls.Add(btnClickMe)
  End Sub

  Private Sub btnClickMe_Click(ByVal sender As Object,
   
ByVal e As System.EventArgs) Handles btnClickMe.Click
   
MessageBox.Show("Clicked!")
 
End Sub
End
Class

Now, one gotchya is that the WithEvents keyword can only be used for fields (local variables need not apply). When you wish to handle an event for a local variable, you are required to use the AddHandler statement.  Here, you will specify the event name and method to call (via the AddressOf operator).  However, in this case the Handles clause is not used.  Here is a re-working of the previous class which illustrates these points: 

Class MainWindow

Inherits Form
 
Public Sub New()
   
Dim btnClickMe As Button
   
btnClickMe = New Button With {.Height = 100,
      .Width = 100, .Text =
"OK!"}

   
AddHandler btnClickMe.Click, AddressOf btnClickMe_Click
    
Me.Controls.Add(btnClickMe)
 
End Sub
...
End Class

Of course, with the release of .NET 4.0, VB has full support for lambda expressions.  This is yet another way to hook into event sources, which was covered in a previous blog post.


Posted by: Andrew Troelsen
Posted on: 6/1/2010 at 10:03 AM
Categories: .NET
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed
Comments are closed
Contact Us 651-994-8558 1-800-866-9884
Home | Training | Curriculum | Course Finder | Schedule | Enroll | Twin Cities Java User Group | Consulting | Foundation | Jobs | About Us | Our Story | Press Room | Instructors | President | Map & Directions | Sitemap

Java Training | JSF / Struts / Spring / Hibernate Training | Java Power Tools Training | .NET 4.0 & Visual Studio 2010 Training | .NET 3.5 and Visual Studio 2008 Training | .NET 2.0 and Visual Studio 2003 Training | Prism / MVVM / MEF Training | Microsoft Web Development Training | Cloud Computing Training | Ajax / Web Services / XML Training | Groovy and Grails Training | SQL Server 2008 Training | SQL Server 2005 Training | Mobile Development Training | SharePoint 2010 Training | SharePoint 2007 Training | Agile, Process, Analysis & Design Training | Arch/Design Patterns Training | Microsoft Official Curriculum Training | Web Development Training | Ruby Training | Rational Application Developer (RAD) Training | WebSphere Application Server Training | WebSphere Portal Training | WebLogic Training | Boot Camp Training | Project Management Training | C++ Training | Metro / WinRT / Windows 8 Development Training | Retired

Intertech delivers training on-site and virtually serving cities including Phoenix, AZ | San Francisco, CA | Los Angeles, CA | San Diego, CA | San Jose, CA | Washington, DC | Chicago, IL | Orlando, FL | Boston, MA | Duluth, MN | Minneapolis St. Paul, MN | Rochester, MN | Raleigh-Durham, NC | New York, NY | Philadelphia, PA | Austin, TX | Dallas, TX | Houston, TX | Seattle, WA.