Select Case Statement in Visual Basic

Format of the Select Case

Select Case TestExpression
        [Case expressionlist1
                statementblock]
        [Case expressionlist2
                statementblock]
        [Case Else
                statementblock]
End Select

 

The TestExpression can be any variable or expression, usually a variable.

The Expression List can be

a value                    Case 1
a list of values        Case “red”, “yellow”
a range of values    Case 1 to 10
a comparison          Case Is > 5
a combination         Case 1, 4 to 8, is > 12

The TestExpression and Expression List should be the same data type.

Each TestExpression is tested in the order they appear. As soon as an expression list satisfies the test expression the statement or statements that follow are executed and control passes to the statement following the End Select.

If TestExpression matches an ExpressionList expression in more than one Case clause, only the statements following the first match are executed.

The Case Else statement is optional. If none of the expression lists satisfy the TestExpression the statement following the Case Else is executed.

 

Select Case intGrade
        Case 100             'equality Implied    this assumes maximum value of 100
                lblGrade.Text= “Perfect Score”
        Case Is > 89        
'The word Is is required with relational operators
                lblGrade.Text= “Grade = A”
        Case 80 To 89   
 'specific range identified
                lblGrade.Text= “Grade = B”
        Case Is > 69
                lblGrade.Text= “Grade = C”
        Case Is > 59
                lblGrade.Text= “Grade = D”
        Case Else
                lblGrade.Text= “Grade = F”
End Select

intTotGrade += intGrade    'using += operator is same as  intTotGrade = intTotGrade + intGrade