Create Loops in ASP

Loops allow you to execute the same section of code again and again thereby saving you time and cutting down on the amount of code you have to write. VBscript has 2 main types of loops.

The For...Next loop

The For...Next loop lets you specify the number of times you want the loop to execute.

<%
For i=1 to 5     ' use i as a counter
response.write i & "<br>"
next     'repeat the code and move on to the next value of i
%>

The code prints out 1 to 5, the <br> tag puts a line break in between each value;

1
2
3
4
5

The Do...Loop

The Do...Loop allows you to loop while a condition is true or until a condition becomes true

The Do While...Loop

<%
'first of all assign a value to i
i=1
Do While i<9
response.write i & "<br>"
i=i+1    'increment the value of i for next time loop executes
Loop
%>

What the above code does is simply print out the following;

1
2
3
4
5
6
7
8

The Do Until ...Loop

<%
'first of all assign a value to i
i=1
Do Until i=9
response.write i & "<br>"
i=i+1    'increment the value of i for next time loop executes
Loop
%>

Again What the above code does is simply print out the following;

1
2
3
4
5
6
7
8

Exiting the Loop

If you want to exit the loop then VBscript allows you to;

<%
For i=1 to 100
response.write i & "<br>"
If i= 99 Then Exit For    'just before 100 is printed out the loop is exited
Next
%>

ASP/.NET Hosting

ASP.NET Web Hosting – 3 Months Free!

MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.