Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 7 Using Loops and Timers 189



  1. Click OK to display the next face.


Your screen looks something like this:


  1. Click OK three more times to see the entire face collection.


You can repeat the sequence if you want.


  1. When you’re finished, click the Close button on the form.


The program stops, and the development environment returns.

Using a Counter That Has Greater Scope

Are there times when using a For... Next loop isn’t that efficient or elegant? Sure. In fact,
the preceding example, although useful as a demonstration, was a little hampered by the
intrusive behavior of the message box, which opened four times in the For... Next loop and
distracted the user from the form, where we want his or her attention to be. Is there a way
we can do away with that intrusive message box?

One solution is to remove both the MsgBox function and the For... Next loop, and substitute
in their place a counter variable that has greater scope throughout the form. As you learned
in Chapter 5, “Visual Basic Variables and Formulas, and the .NET Framework,” you can declare
a variable that has scope (or maintains its value) throughout the entire form by placing a Dim
statement for the variable at the top of the form in the Code Editor—a special location above
the event procedures. In the following exercise, you’ll use an Integer variable named Counter
that maintains its value between calls to the Button1_Click event procedure, and you’ll use
that variable to open the same icon files without using the MsgBox function to pause the
action.
Free download pdf