Test Your Smarts!

Modify the program so that the foreground color on the green button is green, and the foreground color on the blue button is blue. When the form starts out, it should look like what you see on the right.

The key is to set the ForeColor property of the green button to Color.Green, and so something similar for the blue button. You can do this in the event handler for the Form Load event.

Not quite sure how to do this? Talk to your neighbors, or to the instructor for some ideas!

If Statements: Look Ma, just one event handler!

The example we just looked at uses a separate event handler for each button. Sometimes, we want to use a single event handler to respond to multiple events on multiple controls. Let us see how we can use a single event handler in the ColorChanger program.

Begin by deleting all event handlers in the form, to leave the following. That is, you just have a Form class with no methods:

Public Class Form1
End Class

Now double-click on the green button to get a skeleton for click-event handler on the green button:

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

    End Sub
End Class

Because the line is getting too long, we have put a space at the end of the line, followed by an underscore _. When we do this, Visual Basic allows us to continue the statement on the next line.

Previous Next