300 Part II Programming Fundamentals
This For Each... Next loop steps through the Controls collection on the form one
control at a time and sets each control’s Text property to “Click Me!” The loop uses ctrl
as an object variable in the loop, which you’ll declare in the following step.
- Scroll to the top of the form’s program code, and directly above the statement Public
Class Form1, type the following statement:
Option Infer Off
This statement tells the compiler that it should not try to infer the type of variables.
Since you will be explicitly declaring the variable types, this infer option is not
needed. If Option Infer is on and you try to run the code in this chapter, you may see
a warning message indicating that the type for a variable you are using cannot be
inferred. (For more information, see Chapter 1, “Exploring the Visual Studio Integrated
Development Environment .”) - Directly below the statement Public Class Form1, type the following comment
and variable declaration:
'Declare a variable of type Control to represent form controls
Dim ctrl As Control
This global variable declaration creates a variable in the Control class type that
represents the current form’s controls in the program. You’re declaring this variable in
the general declarations area of the form so that it is valid throughout all the form’s
event procedures.
Now you’re ready to run the program and change the Text property for each button on
the form. - Click the Start Debugging button on the Standard toolbar to run the program.
- Click the first button on the form (Button1).
The Button1_Click event procedure changes the Text property for each control in the
Controls collection. Your form looks like this: