More on If Statements and Event Handlers

Now notice that this method handles only the Click event on the GreenButton. To make it handle the Click on the BlueButton too, modify the handles clause as shown here:

Public Class Form1
    Private Sub GreenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles GreenButton.Click, BlueButton.Click 

    End Sub
End Class

That is, you just add the new control.event combination at the end of the handles clause.

Now, we want to the handler to determine which button was just Clicked. If the GreenButton, we set the form's BackColor to Colors.Green, otherwise, we set it to Colors.Blue

How to determine which button was clicked? This is where the sender of the event comes in. If you look at the handler method, you will see that inside the parenthesis are what we call parameters or arguments of the method. The parameters carry information that the method can use in responding to the event. In particular, the sender parameter gives the identity of the button that was the source of the click event that caused the method to be called.

Public Class Form1
    Private Sub GreenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles GreenButton.Click, BlueButton.Click 

    End Sub
End Class

Here is where we use Visual Basic's if statement. We compare the sender parameter (which is an object) to the GreenButton and BlueButton objects. To compare objects to see if they are the same object, you must use the keyword Is. Here is the code

Public Class Form1
    Private Sub GreenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles GreenButton.Click, BlueButton.Click
        If sender Is GreenButton Then
            BackColor = Color.Green
        End If
        If sender Is BlueButton Then
            BackColor = Color.Blue
        End If
    End Sub
End Class


Previous Next