The If Then control structure can be used to run a line or block
of code within your script when a certain condition is met.
Below are 4 ways to use the If Then control structure.
| 1) syntax: | If Condition Then statement End If |
Example 1:
What we have done in example 1 is declared 2 variables A and B and assigned them values. We have used the If Then control structure and if our Condition ie A=B is true then the text A is equal to B will be written out. As is obvious 2 is equal to 2 so the condition is true and our text is written.
In our example 1 what would have happened if B had equalled 3. The condition would not have been true. To accomodate this scenario you could introduce the optional Else clause as in the syntax below.
| 2) syntax: | If Condition Then statement Else statement End If |
Example 2:
In example 2 we have declared 2 variables A and B and assigned them values. As our Condition ie A=B is false our Else clause comes into play and the text A is not equal to B will be written out.
Let's now introduce the Elseif clause.
| 3) syntax: | If Condition1 Then statement ElseIf Condition2 Then statement ElseIf Condition3 Then statement Else statement End If |
Example 3:
In our example 3 we introduce the ElseIf clause which lets us test a series of conditions. If one of the conditions is met (true) then its statement will be executed. As in example 3 none of the conditions are met so our 'catchall' using the Else clause comes into play. This will write out A doesn't equal any of them.
| 4) syntax: | If Condition Then Statement |
Example 4:
In Example 4 we can leave out the End If clause if we only have one statement to perform and you don't want to run any statement at all if the condition is false. It's similar to example 1 though there is no End if and the code is written on the one line.
Rather than use ElseIf in example 3 many programmers will choose to use 'Select Case' if there are alot of options. Read more about Select Case.
Get the best asp web hosting provider now and save 30%
Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.