ASP Select Case
In the previous lesson you
learned how to setup a block of If
Statements using the ElseIf
keyword, but this is not the most
efficient method for checking
multiple conditions. ASP uses the
Select Case statement to check for
multiple Is Equal To "="
conditions of a single variable.
If you are an experienced
programmer you realize the Select
statement resembles a Switch
statement that other programming
languages use for an efficient way
to check a large number of
conditions at one time.
ASP Select Case Example
The variable that appears
immediately after Select Case is
what will be checked against the
list of case statements. These
case statements are contained
within the Select Case block of
code. Below is an ASP Select Case
example that only checks for
integer values. Later we will show
how to check for strings.
ASP Code:
<%
Dim myNum
myNum = 5
Select Case
myNum
Case 2
Response.Write("myNum
is Two")
Case 3
Response.Write("myNum
is Three")
Case 5
Response.Write("myNum
is Five")
Case Else
Response.Write("myNum
is " & myNum)
End Select
%> |
Display:
ASP Select Case - Case Else
In the last example you might
have noticed something strange,
there was a case that was referred
to as "Case Else". This case is
actually a catch all option for
every case that does not fit into
the defined cases. In english it
might be thought of as: If all
these cases don't match then I'll
use the "Case Else"!
It is a good programming
practice to always include the
catch all Else case. Below we have
an example that always executes
the Else case.
ASP Code:
<%
Dim myNum
myNum = 454
Select Case myNum
Case 2
Response.Write("myNum is Two")
Case 3
Response.Write("myNum is Three")
Case 5
Response.Write("myNum is Five")
Case Else
Response.Write("myNum is " & myNum)
End Select
%>
Display:
Select Case with String
Variables
So far we have only used
integers in our Select Case
statements, but you can also use a
string as the variable to be used
in the statement. Below we Select
against a string.
ASP Code:
<%
Dim myPet
myPet = "cat"
Select Case myPet
Case "dog"
Response.Write("I own a dog")
Case "cat"
Response.Write("I do not own a cat")
Case Else
Response.Write("I once had a cute goldfish")
End Select
%>
Display:
|