Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

128 Part II Programming Fundamentals


The form contains two labels and two buttons. You’ll use variables to display
information in each of the labels.

Note The label objects look like boxes because I set their BorderStyle properties to Fixed3D.


  1. Double-click the Show button.


The Button1_Click event procedure appears in the Code Editor.


  1. Type the following program statements to declare and use the LastName variable:


Dim LastName As String

LastName = "Luther"
Label1.Text = LastName

LastName = "Bodenstein von Karlstadt"
Label2.Text = LastName
The program statements are arranged in three groups. The first statement declares
the LastName variable by using the Dim statement and the String type. After you
type this line, Visual Studio places a green jagged line under the LastName variable,
because it has been declared but not used in the program. There is nothing wrong
here—Visual Studio is just reminding you that a new variable has been created and is
waiting to be used.

Tip If the variable name still has a jagged underline when you finish writing your program, it
could be a sign that you misspelled a variable name somewhere within your code.

The second and third lines assign the name “Luther” to the LastName variable and
then display this name in the first label on the form. This example demonstrates
one of the most common uses of variables in a program—transferring information
to a property. As you have seen before, all string values assigned to variables are
displayed in red type.
The fourth line assigns the name “Bodenstein von Karlstadt” to the LastName variable
(in other words, it changes the contents of the variable). Notice that the second string
is longer than the first and contains a few blank spaces. When you assign text strings
to variables, or use them in other places, you need to enclose the text within quotation
marks. (You don’t need to do this with numbers .)
Finally, keep in mind another important characteristic of the variables being declared
in this event procedure—they maintain their scope, or hold their value, only within the
event procedure you’re using them in. Later in this chapter, you’ll learn how to declare
variables so that they can be used in any of your form’s event procedures.
Free download pdf