190 Part II Programming Fundamentals
Use a global counter
- Open the Code Editor for the My For Loop Icons project.
- Move the insertion point above the Button1_Click event procedure, and directly below
the Public Class Form1 statement, declare an Integer variable named Counter by using
this syntax:
Dim Counter As Integer = 1
Notice that Visual Studio separates the declaration that you’ve just entered from the
event procedure with a solid line and displays the word “(Declarations)” in the Method
Name list box. You’ve also done something unusual here—in addition to declaring
the Counter variable, you’ve also assigned the variable a value of 1. Declaring and
assigning at the same time has been a handy feature of Visual Basic since version 2002.
In Chapter 5, I used this syntax to declare a constant, but this is the first time that I’ve
used it for variable declarations.
- Within the Button1_Click event procedure, change the code so that it precisely matches
the following group of program statements. (Delete any statements that aren’t here .)
PictureBox1.Image = System.Drawing.Image.FromFile _
("c:\vb10sbs\chap07\face0" & Counter & ".ico")
Counter += 1
If Counter = 5 Then Counter = 1
As you can see, I’ve deleted the declaration for the i integer, the For and Next
statements, and the MsgBox function, and I’ve changed the way the FromFile method
works. (I’ve replaced the i variable with the Counter variable .) I’ve also added two
new statements that use the Counter variable. The first statement adds 1 to Counter
(Counter += 1), and the second statement resets the Counter variable if the value has
been incremented to 5. (Resetting the variable in this way allows the list of icon files to
cycle indefinitely .) The Counter += 1 syntax is a shortcut feature in Visual Basic 2010—
the functional equivalent of the following statement:
Counter = Counter + 1
Now you’ll run the program.
Tip The modified For Loop Icons program is available in the C:\Vb10sbs\Chap07\For Loop
Icons folder.
- Click the Start Debugging button on the Standard toolbar to run the program.
The program runs in the development environment.
- Click the Display Four Faces button several times. (Notice how the mood of the faces
develops from glum to cheery, as shown here .)