Page

5.4.1- If...Then Control Structure

  by NT Community Manager.
Last Updated  by Jim Minatel.  

PublicCategorized as 05. ASP Control Structures.

Not tagged.
<< 5.4.0- Branching Statements Chapter5 5.4.2- Select Case >>

If...Then Control Structure

The If...Then statement  has four parts:

 

  • An expression: that is, a test that gives a true or false answer
  • An "if true" section of code
  • An "if false" section of code
  • An ending statement

 

The first part is the expression, which can be a combination of keywords, operators, variables, and constants that yield a result as a string, number, or object. We came across them first in the last chapter . It must answer either true or false. If the test answers true, then the lines of code in the "if true" section are executed. If the test answers false, then the lines of code in the "if false" section are executed. After the 'true' or 'false' section is executed the execution jumps down to the ending statement and continues with the next line of code. There is never a situation where both the true and the false sections would be used in a given case.

There are four ways of building If...Then statements. To select the proper syntax you must answer two questions:

 

  • Do I want to do anything if the test is false?
  • Do I want to execute more than one statement if the test is true?

 

The first and most simple way is used if you only have one statement to perform in the case of a 'true' test. You want to execute no statements at all if the test is false. For example, If varFaxConfirm = "Yes", then you want to print the fax number. If the expression evaluates to 'no' then you don't want to do anything. In this most simple case, you can use the one-line syntax:

 

<%

If varFaxConfirm = "Yes" then Response.Write "Please enter your fax number."

%>

 

The next, more complex level, is where you want to perform more than one statement in the case of truth, but still nothing if the test is false. For example, if varFaxConfirm = "Yes", then ask for the fax number and jump over to the fax entry page. In this case we must write the If...Then with two changes from case one above: the statements must go on their own lines, not the same as the simple If...Then example above. And, since there is now more than one line for the If...Then code, we must use a closing line of End If:


 


<%


  If varFaxConfirm = "Yes" Then


    Response.Write ("Please click below and provide your fax number.")


    Response.Write "<A href=http://www.On-LineClothier.com/FaxForm>Click here</A>"


  End If


%>

 

The third level is where you want to perform more than one statement in the case of 'true', and also one or more lines of code if the test is false. For example, if varFaxConfirm = "Yes" then ask for the fax number and jump over to the fax entry page. If varFaxConfirm is anything other than "Yes" then show a line that says that a fax will not be sent. In this situation we must write the If...Then with a line called Else to separate the code that is run in the true case from the code that will run in the false case.

 

<%

  If varFaxConfirm = "Yes" then

    Response.Write "Please enter your fax number."

  Else

    Response.Write "No fax confirmation will be sent."

  End If

%>

There is a fourth level, which we don't recommend using unless you have a specific set of constraints. It allows you to continually nest statements using ElseIf. To use ElseIf, you need to separate each new case with the keyword ElseIf (one word), closing the condition as normally with End If. For example, it can be structured a bit like this:

 

<%

  If varConfirm = "Fax" then

    Response.Write "Please enter your fax number."

  ElseIf varConfirm = "Email" then

    Response.Write "Please enter your email address"

  ElseIf varConfirm = "Voicemail" then

    Response.Write "Please enter your voice mail number"

  Else

    Response.Write "No confirmation will be sent."

  End If

%>

 

Here we test the data to see if it meets condition 1; if it doesn't, we test it to see if it meets condition 2; if it doesn't, we test it to see if it meets condition 3, and so on. When our data meets one of the criteria, or the criteria isn't met, the branch is decided and we arrive at a suitable outcome.

 

There is an alternative structure that provides a simpler solution to this same problem, and we'll be looking at this shortly.

Summary of Four kinds of If...Then Control Structures

Situation

Syntax

Example

Notes for use

If test is true

do one statement

otherwise do nothing

If test Then
 
statement

If strAge < 18 Then

Response.Write "You must be 18 or older to order by credit card."

If you want nothing to happen in the False case

And

You only want one statement to run in the true case

If the test is true

  do two or more
  statements

If the test is false do nothing

If test Then

  True code line 1
  True code line 2

End If

If strAge <18 Then

Response.Write "You must be 18 or older to order by credit card."
Display graphic

End If

 

 

Situation

Syntax

Example

Notes for use

If the test is true

do one or more
statements

If the test is false

do a different set of one or more
statements

If test Then

  True code line 1
  True code line 2

Else

  False code line 1
  False code line 2

End If

If strAge <18 Then

Response.Write "You are eligible for the student rate of $49."

Else

Response.Write "The fee for this service is $59."

End If

 

If the first test is true do one or more statements

else if the second test is true

do a different set of one or more
statements

else if the nth test is true

do a different set of one or more
statements

If test Then

  True code line 1
  True code line 2

ElseIf

  True code line 1
  True code line 2

ElseIf
  True code line 1
  True code line 2

End If

If strAge <18 Then

Response.Write "You are eligible for the student rate of $49."

ElseIf strAge> 65 Then

Response.Write "You are eligible for the senior rate of $49."

ElseIf strAge>18 And strAge<65 Then

Response.Write "The fee for this service is $59."

End If

 

 

When using the one-line form of If...Then you do NOT use End If.
When using any multi-line form of If...Then you MUST use End If

 

So let's now look at an example where you're responsible for notifying your colleagues of the date and location for the Corporate Spring Retreats that we introduced in Chapter 3 .

 

Try It Out – If...Then

1.    There will be four meetings: two on March 15th running in Malibu, California and Myerstown, Pennsylvania, and two on April 16th in the same two cities. Your goal is to design a form that gathers user preferences for month and location, and then provide a response that confirms the date and city. We'll start by creating the form to gather user information. Open your web page editor and type in the following:

<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="IfThenOneResponse.asp" METHOD="post">

Please type your preference in month, either March or April:<BR>

<INPUT TYPE="text" NAME="MonthPref"><P>

Please type your preference in location, either East or West:<BR>

<INPUT TYPE="text" NAME="Location">

<BR>

<BR>

<INPUT TYPE="submit">

<INPUT TYPE="reset">

</FORM>

</BODY>

</HTML>

 

2.    Save this page as IfThenOneForm.asp.

3.    Close that page down. Next, we'll create the response page:

<HTML>

<HEAD>

<TITLE>Spring Retreat Response</TITLE>

</HEAD>

<BODY>

<%

  varMonthPref = Request.Form("Month")

  varLocation = Request.Form("Location")

 

  Response.Write "<H1>Corporate Retreat Registration <BR>Your Details</H1>"

 

  If varMonthPref="March" Then

    Response.Write "Your meeting will be held on March 15th "

  Else

    Response.Write "Your meeting will be held on April 16th "

  End If

 

  If varLocation="East" Then

    Response.Write "in Myerstown, Pennsylvania"

  Else

    Response.Write "in Malibu, California"

  End If

%>

</BODY>

</HTML>

 

4.    Save this as IfThenOneResponse.asp in your BegASPFiles directory.

5.    Open up the page IfThenOneForm.asp in your web browser:

 

Chapter5_image002

 

6.    If you type in March and West and submit your query, you'd come up with the following:

 

Chapter5_image003

How It Works

The form simply follows the guidelines of Chapter 3 .

 

<FORM ACTION="IfThenOneResponse.asp" METHOD="post">

Please type your preference in month, either March or April:<BR>

<INPUT TYPE="text" name="MonthPref"><P>

Please type your preference in location, either East or West:<BR>

<INPUT TYPE="text" name="Location">

<BR><BR><INPUT TYPE="submit"> <INPUT TYPE="reset">

</FORM>

 

The important points to remember in the code are:

 

  • The ACTION attribute of the <FORM> tag must equal the URL of the page the server will return when the submit button is pressed
  • You must use METHOD=Post in the <FORM> tag
  • Always include INPUTs of TYPE "submit" and "reset"
  • Each input must have a name, in this case MonthPref and Location

 

The response page is where we use the control structure If...Then. The page starts with the basic <HEAD> tags, then immediately starts the ASP VBScript code. The first job is to pass the information typed by the user into variables named varMonthPref and varLocation using the technique covered in the last chapter .

 

<%

  varMonthPref = Request.Form("MonthPref")

  varLocation = Request.Form("Location")

 

Then we use Response.Write to get some text on the page.

 

  Response.Write "<H1>Corporate Retreat Registration <BR>Your Details</H1>"

 

The first control structure checks the contents of varMonthPref to see if it contains the word "March". Since that is a proper expression, it can be answered with a true or false. If it is true then two things happen:

 

  • The true section of code is executed to put " …March 15th" onto the HTML page
  • VBScript skips the false line of code ("…April 16th") and jumps down to after the End If

 

If the expression is false (if the value entered isn't "March" we assume it to be "April") then VBScript will do the following:

 

  • Skip the true section of code ("…March 15th")
  • Perform the false section of code ("…April 16th") and continue on down through the End If

 

  If varMonthPref="March" Then

    Response.Write "Your meeting will be held on March 15th "

  Else

    Response.Write "Your meeting will be held on April 16th "

  End If

 

The second If...Then works the same way. If it is true that varLocation is "East" then VBScript executes the writing of the city – Myerstown, Pennsylvania – and then jumps down to the line after End If. If VarLocation="East" is false we assume that the user typed "West" and so we skip the Myerstown line and go to the Malibu line.

 

  If varLocation="East" Then

    Response.Write "in Myerstown, Pennsylvania"

  Else

    Response.Write "in Malibu, California"

  End If

Common Errors of the If...Then Statement

There are several common errors that we can make when creating an If...Then statement:

 

  • Devising a test that does not resolve to True or False
  • Try to use more than one statement with the one-line version of the If...Then construct.
  • Leave out the End If when using the block version of the If...Then construct
  • Leave out the Else
  • Code End If as EndIf
  • Basic Rules of If...Then

  • You can only evaluate one expression (do one test) in an If...Then structure
  • There are only two possible results from the expression: True or False
  • You can only use one statement in the one-line version of If...Then
  • You can have multiple tests in If...Then...Else if you utilize ElseIf.
  • If there is more than one line of action statements then you must use the End If
  • If you want action in the case of a false result then you must use an Else line
<< 5.4.0- Branching Statements Chapter5 5.4.2- Select Case >>

Copyright © 2003 by Wiley Publishing, Inc.

Powered by Near-TimeTerms of Services | Privacy Policy | Security Policy |