ASP Hosting sale!
1,000MB space, 40GB transfer, 1 SQL Server 2000 db! - $9.95 per month*!
Limited Time Offer!

aspdev | articles | tutorials | forums

ASPdev -> ASP Tutorial -> ASP Conditional Statements (VBScript)

ASP Conditional Statements (VBScript)

You can control the programming execution flow of your scripts, by using VBScript conditional statements. VBScript has 2 conditional statement constructions, available for you to use in your ASP pages:

If…Then…Else conditional statement
Select Case conditional statement


If…Then…Else conditional statement

The If…Then…Else statement evaluates a condition to True or False. Depending on this evaluation result, you specify one or more programming statements to run. You can nest If…Then…Else statements as deep as you like.

Here is an example of If…Then…Else statement in its simplest form:

If x > y Then x = y

The statement above simply evaluates the x > y expression and if the result is True it assign the x variable the value of y. You may have noticed that the Else part of the If…Then…Else statement was not presented above, that’s why if x > y returns False no programming code is executed. The Else part of the If…Then…Else statement is optional.

Consider the following example:

If x > y Then
x = y
Else
y = x
End If

In this example, we again evaluate the same expression, but now we execute different lines of code, depending on the result of the evaluation.

One of the forms of the If...Then...Else statement allows to choose from numerous options. Here is an example:


If sDay = “Saturday” Then
MsgBox “1st day of the weekend”
ElseIf sDay = “Sunday” Then
MsgBox “2nd day of the weekend”
Else
MsgBox “Week day”
End If

By adding ElseIf we expand the If...Then...Else statement with additional program flow control option. You can have as many ElseIf statements as you need, but if you need more than 2-3, you are better of using the Select Case conditional statement.


Select Case conditional statement

The Select Case conditional statement has very similar functionality to the If...Then...Else statement. By using Select Case instead of If...Then...Else (where appropriate) you make your code easier to read and more efficient as well.

Consider the following Select Case example, which does the same as the last If…Else…Then example we discussed:

Select Case sDay
Case "Saturday"
MsgBox “1st day of the weekend”
Case "Sunday"
MsgBox “2nd day of the weekend”
Case Else
MsgBox “Week day”
End Select

A Select Case statement evaluates only one expression, at the top of the statement. The result of the expression is consequently compared with the values of each Case from the top to the bottom. If there is a match for certain Case, the programming code following that Case is executed.

As you can see for yourself, the Select Case solution is much more elegant and readable in this situation, compared to the If…Then…Else construction.




Contact Us