162 Part II Programming Fundamentals
in the program and take a course of action based on the result. In its simplest form,
an If... Then decision structure is written on a single line:
If condition Then statement
where condition is a conditional expression, and statement is a valid Visual Basic program
statement. For example:
If Score >= 20 Then Label1.Text = "You win!"
is an If... Then decision structure that uses the conditional expression:
Score >= 20
to determine whether the program should set the Text property of the Label1 object to “You
win!” If the Score variable contains a value that’s greater than or equal to 20, Visual Basic
sets the Text property; otherwise, it skips the assignment statement and executes the next
line in the event procedure. This sort of comparison always results in a True or False value.
A conditional expression never results in a value of maybe.
Testing Several Conditions in an If... Then
Decision Structure
Visual Basic also supports an If... Then decision structure that you can use to include several
conditional expressions. This block of statements can be several lines long and contains the
important keywords ElseIf, Else, and End If:
If condition1 Then
statements executed if condition1 is True
ElseIf condition2 Then
statements executed if condition2 is True
[Additional ElseIf conditions and statements can be placed here]
Else
statements executed if none of the conditions is True
End If
In this structure, condition1 is evaluated first. If this conditional expression is True, the block
of statements below it is executed, one statement at a time. (You can include one or more
program statements .) If the first condition isn’t True, the second conditional expression
(condition2) is evaluated. If the second condition is True, the second block of statements
is executed. (You can add additional ElseIf conditions and statements if you have more
conditions to evaluate .) If none of the conditional expressions is True, the statements below
the Else keyword are executed. Finally, the whole structure is closed by the End If keywords.
The following code shows how a multiple-line If... Then structure could be used to
determine the amount of tax due in a hypothetical progressive tax return. (The income
and percentage numbers are from the projected U .S. Internal Revenue Service 2010 Tax Rate
Schedule for single filing status .)