The sentence that is displayed depends upon the age the user enters. As you see, the Select Case statement begins with the line:
Select Case <expression>That expression is evaluated, and instructions are provided for each Case (value range) the programmer is interested in. In this example, we have four Cases, each of which displays a different sentence. Note that the Case lines can have one of two forms: Case <expression> to <expression>or Case Is <relational operator> <expression>Note that the Select Case statement ends with End Select |
Dim intAge As Integer 'the user's age intAge = CInt(txtAge.Text) Select Case intAge Case Is <= 10 lblStage.Text = "You are mighty cute." Case 11 To 20 lblStage.Text = "You are going to school." Case 21 To 30 lblStage.Text = "You are working hard." Case Is > 30 lblStage.Text = "You are over the hill." End Select |
The Cases can also involve string expressions, as illustrated by this academic advisor program:
This program gives feedback that depends on the grade the user enters. It works for both upper and lower case letters, and, if the user does not give a valid grade, it displays an error message.
While there is only one instruction for each case in this example, there can be as many as you wish. For example, the program could send an e-mail to the student's parents after it displayed the messages for grades D or F. Instead of a simple <expression>, the Case Is lines contain lists of <expression>s to compare to. The Case is true if any of the tests are true. (This is like using the Boolean operator or). Finally, note the last case, Case Else. The Case Else instructions are a catch-all. They are executed if none of the other conditions is true |
Dim strGrade As String 'the user's grade strGrade = txtGrade.Text Select Case strGrade Case Is = "a", "A" lblFeedback.Text = "Way to go, excellent!" Case Is = "b", "B" lblFeedback.Text = "Very good." Case Is = "c", "C" lblFeedback.Text = "Is this your major?" Case Is = "d", "D", "f", "F" lblFeedback.Text = "Better take it again." Case Else lblFeedback.Text = "Grades must be a, b, c, d or f." End Select |
As you see, the Select Case statement allows you to create multi-branch programs, but the complexity of the Boolean expression you test is somewhat limited relative to the If statements. With the If statements, you can test any Boolean expression.