Select Case Decision Structures


Select Case Decision Structures

With Visual Basic, you can also control the execution of statements in your programs by using Select Case decision structures. You used Select Case structures in Chapters 3 and 5 of this book when you wrote event procedures to process list box and combo box choices. A Select Case structure is similar to an If…Then…ElseIf structure, but it's more efficient when the branching depends on one key variable, or test case. You can also use Select Case structures to make your program code more readable.

The syntax for a Select Case structure looks like this:

Select Case variable      Case value1          statements executed if value1 matches variable      Case value2          statements executed if value2 matches variable     Case value3          statements executed if value3 matches variable     …      Case Else           statements executed if no match is found End Select

A Select Case structure begins with the Select Case keywords and ends with the End Select keywords. You replace variable with the variable, property, or other expression that is to be the key value, or test case, for the structure. You replace value1, value2, and value3 with numbers, strings, or other values related to the test case being considered. If one of the values matches the variable, the statements below the Case clause are executed, and then Visual Basic jumps to the line after the End Select statement and picks up execution there. You can include any number of Case clauses in a Select Case structure, and you can include more than one value in a Case clause. If you list multiple values after a case, separate them with commas.

The following example shows how a Select Case structure could be used to print an appropriate message about a person's age and cultural milestones in a program. Since the Age variable contains a value of 18, the string “You can vote now!” is assigned to the Text property of the label object. (You'll notice that the “milestones” have an American slant to them; please customize freely to match your cultural setting.)

Dim Age As Integer  Age = 18    Select Case Age      Case 16          Label1.Text = "You can drive now!"      Case 18          Label1.Text = "You can vote now!"      Case 21          Label1.Text = "You can drink wine with your meals."      Case 65          Label1.Text = "Time to retire and have fun!"  End Select

A Select Case structure also supports a Case Else clause that you can use to display a message if none of the preceding cases matches the Age variable. Here's how Case Else would work in the following example—note that I've changed the value of Age to 25 to trigger the Case Else clause:

Dim Age As Integer  Age = 25    Select Case Age      Case 16          Label1.Text = "You can drive now!"      Case 18          Label1.Text = "You can vote now!"      Case 21          Label1.Text = "You can drink wine with your meals."      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 ListBox1.Text and ListBox1.SelectedIndexChanged 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 appears.

  2. Create a new project named My Select Case.

    A blank form appears in the Designer.

  3. Click the Label control in the Toolbox, and then draw a label near the top of the form to display a title for the program.

  4. Use the Label control to create a second label object below the first.

    You'll use this label as a title for the list box.

  5. Click the ListBox control in the Toolbox, and then create a list box below the second label.

  6. Use the Label control to draw two more labels below the list box to display program output.

  7. Use the Button control to create a small button on the bottom of the form.

  8. Open the Properties window, and then set the properties shown in the following table for the objects that you have just created.

    Since there are so many objects, you'll also assign Name properties to help you easily identify the control on the form and within your program code. (You'll find Name listed in parentheses near the top of the Properties window, which allows it to be listed first in the alphabetical list.) I recommend that you use the Name property whenever you have more than four or five objects in a program. In this example, I've given the objects names that feature a three-character prefix to identify the object type, such as btn (for button), lbl (for label), and lst (for list box).

    Object

    Property

    Setting

    Form1

    Text

    “Case Greeting”

    Label1

    Font

    Name

    Text

    Times New Roman, Bold, 12-point

    lblTitle

    “International Welcome Program”

    Label2

    Name

    Text

    lblTextBoxLabel

    “Choose a country”

    Label3

    Font

    Name

    Text

    10-point

    lblCountry

    (empty)

    Label4

    AutoSize

    BorderStyle

    ForeColor

    Name

    Text

    False

    Fixed3D

    Red

    lblGreeting

    (empty)

    ListBox1

    Name

    lstCountryBox

    Button1

    Name

    Text

    btnQuit

    “Quit”

    When you've finished setting properties, your form looks similar to this:

    graphic

    Now you'll enter the program code to initialize the list box.

  9. Double-click the form.

    The Form1_Load event procedure appears in the Code Editor.

  10. Type the following program code to initialize the list box:

    lstCountryBox.Items.Add("England")  lstCountryBox.Items.Add("Germany")  lstCountryBox.Items.Add("Mexico")  lstCountryBox.Items.Add("Italy")

    These lines use the Add method of the list box object to add entries to the list box on your form.

  11. Click the Form1.vb [Design] tab at the top of the Code Editor to switch back to the Designer, and then double-click the list box object on your form to edit its event procedure.

    The lstCountryBox_SelectedIndexChanged event procedure appears in the Code Editor.

  12. Type the following lines to process the list box selection made by the user:

    lblCountry.Text = lstCountryBox.Text  Select Case lstCountryBox.SelectedIndex      Case 0          lblGreeting.Text = "Hello, programmer"      Case 1          lblGreeting.Text = "Hallo, programmierer"      Case 2          lblGreeting.Text = "Hola, programador"      Case 3          lblGreeting.Text = "Ciao, programmatore"  End Select

    The first line copies the name of the selected list box item to the Text property of the third label on the form (which you renamed lblCountry). The most important property used in the statement is lstCountryBox.Text, which contains the exact text of the item selected in the list box. The remaining statements are part of the Select Case decision structure. The structure uses the lstCountryBox.SelectedIndex property as a test case variable and compares it to several values. The SelectedIndex property always contains the number of the item selected in the list box; the item at the top is 0 (zero), the second item is 1, the next item is 2, and so on. By using SelectedIndex, the Select Case structure can quickly identify the user's choice and display the correct greeting on the form.

  13. Display the form again, and double-click the Quit button (btnQuit).

    The btnQuit_Click event procedure appears in the Code Editor.

  14. Type End in the event procedure.

  15. Click the Save All button on the Standard toolbar to save your changes. Specify the c:\vb05sbs\chap06 folder as the location.

    Now run the program, and see how the Select Case statement works.

    TIP
    The complete Select Case project is located in the c:\vb05sbs\chap06\select case folder.

  16. Click the Start Debugging button on the Standard toolbar to run the program.

  17. Click each of the country names in the Choose A Country list box.

    The program displays a greeting for each of the countries listed. The following illustration shows the greeting for Italy:

    graphic

  18. Click the Quit button to stop the program.

    The program stops, and the development environment returns.

You've finished working with If…Then and Select Case decision structures in this chapter. You'll have several additional opportunities to work with them in this book, however. If…Then and Select Case are two of the crucial decision-making mechanisms in the Visual Basic programming language, and you'll find that you use them in almost every program that you write.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net