| << 5.4.1- If...Then Control Structure | Chapter5 | 5.4.3- Looping Controls >> |
Select Case
One problem of If…Then is that it can start getting unwieldy after more than two possible outcomes. What happens if you want to show a different page to visitors from each of five departments? What happens if you want to do a calculation based on the user providing one of twelve salary grades? What happens if you have different procedures for confirming an order by telephone, fax or E-mail? Your code is going to start looking pretty messy with all of those ElseIfs. Select Case is the alternative control structure we mentioned earlier for handling branching and it caters much more neatly for these type of situations, by providing a better structure and extra readability: anytime you need to make a choice among several answers (more than just True and False) then use Select Case.
The syntax for Select Case has four parts:
- State which variable to test
- State a possible answer and what to do if that answer is correct
- Repeat for as many possible answers as you want to handle
- End the Select Case control structure
The first example, below, carries out one of three actions depending on what is contained in the variable varConfirmation.
<%
Select Case varConfirmation
Case "Fax"
Response.Write "<A href='FaxConfirmation.asp'>Fax</A>"
Case "Telephone"
Response.Write "<A href='telephone.asp'>Telephone</A>"
Case "EMail"
Response.Write "<A href='EMail.asp'>Email</A>"
End Select
%>
VBScript will know from the first line that you want to compare answers to the contents of the variable varConfirmation. Next, VBScript will begin testing the contents of the variable against the values shown in the Case lines. When VBScript finds a match it will execute the following code up to the next Case line, and will then jump down to the first line after the End Select statement. You may have noticed in the last Try It Out that if the user typed "march" in lower case then the program failed: it displayed April on the Spring Retreat Response page. This was because we only coded for the possibility of the user typing "March", and printed April in all other cases. You can get by this by accounting for more possibilities, for example march, March, april, April. You can even include a "catch-all" case – for example, what if the user decided to type Saturday? VBScript allows you to write a special test called Case Else, which will run some code if all other conditions fail. For example:
<%
Select Case varMonthPref
Case "march"
Response.Write "Your meeting will be held on March 15th "
Case "March"
Response.Write "Your meeting will be held on March 15th "
Case "april"
Response.Write "Your meeting will be held on April 16th "
Case "April"
Response.Write "Your meeting will be held on April 16th "
Case Else
Response.Write "your request for " & varMonthPref
Response.Write " is not recognized."
Response.Write "Please click the back button on your browser "
Response.Write "and reset then refill the form again.<BR>"
End Select
%>
In this example, the user who decided to type Saturday will receive our own custom error message, telling them to try again.
We can further refine this code by having VBScript test for more than one result on one case line. As an example, for both "march" and "March" we would do the same action (Response.Write "...March 15th"). This syntax is simple, just line up the possible answers separated by commas as demonstrated in the code below:
Select Case varMonthPref
Case "march", "March", "mar", "Mar", "MAR"
Response.Write "Your meeting will be held on March 15th "
Case "april", "April", "apr", "Apr", "APR"
Response.Write "Your meeting will be held on April 16th "
Case Else
Response.Write "your request for " & varMonthPref
Response.Write " is not recognized."
Response.Write "Please strike the back button on your browser "
Response.Write "and reset then refill the form again.<BR>"
End Select
This will work fine, but what if you wanted to test for many different possible inputs? You could end up with having case statements to catch several kinds of input (mar, Mar, march, March, MARCH, etc). VBScript offers a completely different way to solve the case problem. If you change all input text to uppercase before testing, you can reduce the number of tests needed. The Ucase () function will convert a string to all uppercase as follows:
Select Case Ucase(varMonthPref)
Case "MARCH", "MAR"
Response.Write "Your meeting will be held on March 15th "
Case "APRIL", "APR"
Response.Write "Your meeting will be held on April 16th "
Case Else
Response.Write "your request for " & varMonthPref
Response.Write " is not recognized."
Response.Write "Please strike the back button on your browser "
Response.Write "and reset then refill the form again.<BR>"
End Select
So, we've managed to cut down the number of test statements that we need to worry about. However, in some situations, it may become very difficult to account for all the possible answers the user may try to type into the entry field. One alternative is to provide the user with a fixed set of options to choose from, and we can do just that with a special type of input box called a 'drop-down' or 'combo' box. These appear in input forms as follows:
<SELECT NAME="dropbox">
<OPTION VALUE="Option1">One</OPTION>
<OPTION VALUE="Option2">Two</OPTION>
<OPTION VALUE="Option3">Three</OPTION>
<OPTION VALUE="Option4">Four</OPTION>
</SELECT>
By including this on a simple form page, within the <FORM> and </FORM> tags, this would produce a box that looks like this:
|
|
The NAME attribute of the select tag contains the name of the box – this name is used in the same way as we have seen with the text input boxes we've been using so far. What you may notice is that the text displayed can be different to the data that gets used on a result page. In this example, selecting One from the drop box will actually select the value Option1, so if we were using our Select Case structure, you could use the following in a result page:
varDropBox = Request.Form("dropbox")
Select Case varDropBox
Case "Option1"
Response.Write "You chose Option One"
Case "Option2"
Response.Write "You chose Option Two"
Case Else
Response.Write "You chose either Option Three or Option Four
End Select
In this way, you can have a more detailed list of options for your users to choose from, but a simplified list of values that can be used with our Select Case statements
This next Try It Out will use a drop-down box to reply to two questions, and then we'll use Select Case to display appropriate results.
Try It Out – Select Case
We will modify the two pages we used in the If...Then example to use the Select Case structure
1. Open up IfThenOneForm.asp and change the following highlighted line:
<HTML>
<HEAD>
<TITLE>Spring Retreat Form</TITLE>
</HEAD>
<BODY>
<H1>Corporate Retreat Registration</H1>
<H3>To get the logistics information for your meeting please answer these two questions.</H3>
<FORM ACTION="SelectCaseResponse.asp" METHOD="post">
Which month would you prefer?<BR>
<SELECT NAME="MonthPref">
<OPTION VALUE="Jan">January</OPTION>
<OPTION VALUE="Mar">March</OPTION>
<OPTION VALUE="May">May</OPTION>
<OPTION VALUE="Jul">July</OPTION>
<OPTION VALUE="Sep">September</OPTION>
<OPTION VALUE="Nov">November</OPTION>
</SELECT>
<BR><BR>
What is your preferred location?<BR>
<SELECT NAME="Location">
<OPTION VALUE="East">East</OPTION>
<OPTION VALUE="West">West</OPTION>
</SELECT>
<BR><BR>
<INPUT TYPE="submit">
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>
2. Save this as SelectCaseForm.asp
3. Open up the page IfThenOneResponse.asp and change the following highlighted lines:
<HTML>
<HEAD>
<TITLE>Corporate Retreat Response</TITLE>
</HEAD>
<BODY>
<%
varMonthPref = Request.Form("Month")
varLocation = Request.Form("location")
Response.Write "<H1>Corporate Retreat Registration <BR> Your Details</H1>"
Select Case varMonthPref
Case "Jan"
Response.Write "Your meeting will be held on January 14th "
Case "Mar"
Response.Write "Your meeting will be held on March 15th "
Case "May"
Response.Write "Your meeting will be held on May 16th "
Case "Jul"
Response.Write "Your meeting will be held on July 17th "
Case "Sep"
Response.Write "Your meeting will be held on September 18th "
Case "Nov"
Response.Write "Your meeting will be held on November 19th "
End Select
If varLocation="East" then
Response.Write "in Myerstown, Pennsylvania"
Else
Response.Write "in Malibu, California"
End If
%>
</BODY>
</HTML>
4. Save this as SelectCaseResponse.asp
5. Now if you open SelectCaseForm.asp in your browser, you'll find that the example prevents our user from typing in variations of the same month (march, MARCH, March etc.) or location, by supplying them with a list to choose from. After submitting the information, the user will see the corresponding result.
How It Works
The essential change is the replacement of an If...Then structure with a Select Case structure. When VBScript reads the Select Case it knows that ensuing tests will be against varMonthPref. The first possible answer it tries is "Jan" and if that is a match then it does the first Response.Write line, otherwise, it moves on to the next comparison which is for "Mar". If this does not produce a match, then VBScript will drop down to the next Case line and try "May" and so on.
Easy mistakes: Since this form and response are similar to the last Try It Out be careful not to accidentally call the wrong one up in you browser when testing. If you copied the last Try It Out response page and modified it here, be sure you changed the <FORM> ACTION attribute.
Common Errors of the Select Case Structure
- Putting a comparison (= or < or >) on the first Select line. The first line says which variable to compare to, but it is NOT an expression.
- Putting more than one variable on the Select…Case line. For example, ASP will not accept: Select Case varNameFirst, varNameLast.
- Not making the possible answers mutually exclusive.
- Not including Case Else (Case Else is not required, but good programming practice as it can deal with unexpected user inputs).
- Each Case line should have a possible answer. That possible answer must be in quotes if it is text.
- Type Select Case or End Select as one word.
- Forgetting the End Select line
- Finishing the structure with End Case instead of End Select
- Trying to use "Where" or "Is" on a Case line (these comparison operators are only available in VB, and not VBScript).
- Using Select Case to check only two outcomes. For just two outcomes If...Then is faster.
Further Improving your Select Case Structures
Of course, things could get a little out of hand if say for example you were testing not just for a specific month, but for an available day in a given range of days in a specific month. You wouldn't want to type in the following:
Select Case (varDatePref)
Case 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
Response.Write "Your meeting will be held on March 15th "
Case 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
Response.Write "Your meeting will be held on March 30th "
...
End Select
Fortunately, one last trick of Select Case allows you to save your fingers. You can create Boolean expression in the Case part of the expression and depending on whether it evaluates to true or false when supplied with a value, it will choose one of the cases.
Select Case True
Case varDatePref <= 15
Response.Write "Your meeting will be held on March 15th "
Case varDatePref >15
Response.Write "Your meeting will be held on March 30th "
...
End Select
However, you must make sure that it is only possible for one of your expressions at any one time to evaluate to true.
Basic Rules of Select Case
- Use Select...Case for taking action for more than two possibilities.
- The first line states the variable to compare to, but does not define the comparison.
- ASP will execute the code after the first match.
- It is always best to use Case Else to cover unexpected circumstances
We've covered a lot of ground so far in looking at branching controls. Now we'll take a look at our next type of controls: looping controls.
| << 5.4.1- If...Then Control Structure | Chapter5 | 5.4.3- Looping Controls >> |

RSS


