Wednesday, December 12, 2012

Select case in visual basic with example


Select Case: The Select Case structure compares one expression to different values. The advantage of the Select Case statement over multiple If...Then...Else statement is that it makes the code easier to read and maintain.
The Select Case structure tests a single expression, which is evaluated once at the top of the structure. The result of the test is then compared with several values, and if it matches one of them, the corresponding block of statements is executed. Here’s the syntax of the Select Case statement:
               Select Case expression
               Case value1
                  statementblock-1
               Case value2
                  statementblock-2
                 .
                 .
                 .
               Case Else
                  statementblock
               End Select

A practical example based on the Select Case statement is:
Select Case WeekDay(Date)
Case 1
   DayName = “Monday”
   Message = “Have a nice week”
Case 6
   DayName = “Saturday”
   Message = “Have a nice weekend”
Case 7
   DayName = “Sunday”
   Message = “Did you have a nice weekend?”
Case Else
   Message = “Welcome back!”
End Select

The expression variable, which is evaluated at the beginning of the statement, is the number of the weekday, as reported by the WeekDay() function (a value in the range 1 to 7). The value of the expression is then compared with the values that follow each Case keyword. If they match, the block of statements up to the next Case keyword is executed, and the program skips to the statement following the End Select statement. The block of the Case Else statement is optional and is executed if none of the previous Case values match the expression.