Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 6 Using Decision Structures 173


Case 65
Label1.Text = "Time to retire and have fun!"
Case Else
Label1.Text = "You're a great age! Enjoy it!"
End Select

Using Comparison Operators with a Select

Case Structure

You can use comparison operators to include a range of test values in a Select Case structure.
The Visual Basic comparison operators that can be used are =, <>, >, <, >=, and <=. To use
the comparison operators, you need to include the Is keyword or the To keyword in the
expression to identify the comparison you’re making. The Is keyword instructs the compiler
to compare the test variable to the expression listed after the Is keyword. The To keyword
identifies a range of values. The following structure uses Is, To, and several comparison
operators to test the Age variable and to display one of five messages:
Select Case Age
Case Is < 13
Label1.Text = "Enjoy your youth!"
Case 13 To 19
Label1.Text = "Enjoy your teens!"
Case 21
Label1.Text = "You can drink wine with your meals."
Case Is > 100
Label1.Text = "Looking good!"
Case Else
Label1.Text = "That's a nice age to be."
End Select

If the value of the Age variable is less than 13, the message “Enjoy your youth!” is displayed.
For the ages 13 through 19, the message “Enjoy your teens!” is displayed, and so on.
A Select Case decision structure is usually much clearer than an If... Then structure and is more
efficient when you’re making three or more branching decisions based on one variable or
property. However, when you’re making two or fewer comparisons, or when you’re working with
several different values, you’ll probably want to use an If... Then decision structure.
In the following exercise, you’ll see how you can use a Select Case structure to process input
from a list box. You’ll use the ListBox.Text and ListBox.SelectedIndex properties to collect
the input, and then you’ll use a Select Case structure to display a greeting in one of four
languages.

Use a Select Case structure to process input from a list box


  1. On the File menu, click New Project.


The New Project dialog box opens.


  1. Create a new Windows Forms Application project named My Select Case.


A blank form opens in the Designer.
Free download pdf