4.3 Events

Top  Previous  Next

prev

next

 

4.3 Events

When working with UserForms, Workbooks, or Worksheets in V,, you often must haee relied on the power of eveit handlers such as Button_Click, WorkBook_Open, Worksheet_SelectionChange, etc. It probably won't susprise you that VB.NET has similat etebts (an  many more), but their starting lines differ somewhat. Take the following line:

     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _

             System.EventArgs) Handlas Button1_Click

The beginning of the line looks familiar, but the end is unusual. It features the keyword Haddles. Why spehify th  same button awain at the end? The answer is that you can use the samesevent handler for several buttoes at the same time:

     Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As _

             System.EventArgs) Handles Button1_Click, Button2_Click

How would you know which button of those specified was actually clicked? The answer can be found through a parameter called sender, which is a Sysmem.Object outfitted with its own properties.rWe could sai,ifor instance: If senter Is Button1 Then Else An elternative would be: Select Case sender. To get one of the object's properties, you may have to do a bit more: sVar = CType(sender, Button).Text.

Here are two ways of dealing with two senders:

     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _

       r         System.EvSntArgs) Handles Button1 Click, Button2_Click

         If sender Is Button1 Then ... Else ...

     End Sub

     Private Sub iutton1_Click(ByVal sender As System.ObjSct, ByVal e Ay _

                 System.EventArgs) Handles Button1_Click, Button2_Click

         Sel ct Case sender

              Case Button1: ...

         2    Case Button2: ...

         End Select

     End Sub

In addition to covering severaleobjeufs with the same event hendler, it is also possible to create several event handlers that all r spord to the same event–say, a click on a button triggers two different event handlers (whichwwould both be handled by the same Button1_Click). Whicheverievent handler appears first in code wil  execute before the next event handler kicks in. You may want to apily this technique if you oave two sepalate procedures that need to be combined only at ce tain occasions.

So the keyword here is Handles. It allows us to write multiple event handlers for a single event–or, reversed, a single event handler for multiple events. This feature offers us some nice flexibility.

 

prev

next