Tuesday, 28 August 2012

ASP Lesson #3 - Control Structures

If Statement

You can make a decision based on user input using an If statement. The If statement tests a condition and if the result is true then it runs the code that follows the If statement but if the result is false then it runs the code after the else statement. Here is an example for when someone enters their age on a form:

Dim Age
Age = Request("txtAge")
if Age >= 18 then
   Response.Write "You are old enough to use this site"
   Response.Write "You are too young to use this site"
end if

Select Case Statement

The Select Case statement is similar to the If statement because it also used for making decisions. The difference is that the Select Case statement can have many conditions and the code to run for when the result of each condition is true. Here is an example of choosing a country from a dropdown listbox:

Dim Country
Country = Request("lstCountry")
Select Case Location
Case "USA"
   Response.Write "You are from the USA"
Case "UK"
   Response.Write "You are from the UK"
Case "SA"
   Response.Write "You are from SA"
End Select

For Loop

The For loop is used to loop from one number to another. The code inside the loop is repeated until the second number is reached. Here is an example of counting to 10 using a For loop:

Dim i
for i = 1 to 10
   Response.Write i

While Loop

The While loop checks if a condition is true before each time that the code inside the loop is repeated. The loop variable must be set before it is used in a While loop and the loop variable must be incremented inside the loop.
Dim j
j = 1
While j <= 10
   Response.Write j
   j = j + 1

Do Loop

The Do loop is the same as the While loop except that the condition is tested at the bottom instead of at the top of the loop.

dim k
k = 1
   Response.Write k
   k = k + 1
loop until k > 10


Post a Comment