ASP Primer: More Basic VBScript
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
And now on to something new. In this installment we'll make you dizzy by talking about loops. We'll also take a look at arrays and how they relate to tables.
Let's take a look at the FOR .. NEXT loop first. This particular loop is about as straight-forward as it gets. Its job is to start at a certain number and count until it reaches its designated stopping point.
In order to demonstrate how this works, let's take a look at our practical example for this installment of the ASP Primer. Below we will use a FOR .. NEXT loop to populate a drop-down list box on a form. We will be putting in the year, beginning with this year, plus 7 more years for a total of 8. This is a handy little piece of code for populating a credit card drop-down so that you will never have to go back and change the years listed as time goes by. Here it is:
<FORM METHOD="POST" ACTION="thispage.asp">
<SELECT SIZE="1" NAME="year">
<OPTION>Please select a year ...</OPTION>
<% DIM intYearCounter, intCurrentYear %>
<% intCurrentYear = Year(Date) %>
<% FOR intYearCounter = intCurrentYear TO
(intCurrentYear + 7) %>
<% Response.Write "<OPTION>" &
CStr(intYearCounter) & "</OPTION>" %>
<% NEXT %>
You'll notice we are using some of the elements from the last tutorial like the DIM statement. Next you will notice we set our newly created variable, intCurrentYear, to Year(Date). This sets our variable to the current year. This is one of those nifty little functions that is built into VBScript and ASP. We'll cover this function and more later in this series.
Then we have our FOR statement. This is where we define where we will start our loop and how long it will continue looping. First we give it the variable we created above, intYearCounter, so that it can use that variable for storage as it counts. Next we define where we want to begin counting. In our case we will begin counting with the current year which is what is being stored in intCurrentYear. Now that the FOR statement knows where we want to begin we need to tell it when to stop. In our case, we want it to stop after it has run though the loop 8 times. So, we finish the FOR statement by using TO (intCurrentYear + 7).
If you are wondering why we are doing (intCurrentYear + 7) instead of (intCurrentYear + 8) imagine this: suppose our starting year is 2001. We want to display a total of 8 years starting with 2001. Therefore, our last year listed should be 2008. The difference between 2008 and 2001 is 7 which is why we add 7 to intCurrentYear.
The next line that you come to is Response.Write "<OPTION>" & CStr(intYearCounter) & "</OPTION>". What this actually does is take the current number in intYearCounter and combine it with HTML to send to the browser when the page is rendered. We'll get into the particulars of CStr and Response.Write later in this series.
Then there is the NEXT statement. This simply tells the server that this is the end of our FOR .. NEXT loop. The FOR .. NEXT loop only executes the code between the FOR and the NEXT. So, when our loop runs it will only repeatedly execute the line starting with Response.Write since it is the only line inside the loop. Even though we only have one line inside our loop, you can have as many lines as you like.
|A Word of Caution
Don't ever mess with the value of your counter variable (intYearCounter above) inside your FOR .. NEXT loop. Displaying its current value is perfectly acceptable but if you change the value of your counter variable you could very easily confuse your FOR .. NEXT loop and get yourself stuck in an infinite loop.
Now that you know how the basic loop structure works, here's another little thing you can do. You can use STEP to change how your loop increments. Let's say you wanted every other year to be displayed above instead of every year. Try this:
<% FOR intYearCounter = intCurrentYear TO
(intCurrentYear + 7) STEP 2 %>
Now instead of adding 1 (the default) to intYearCounter each time through the loop you will add 2 thus displaying every other year.
Let's suppose you wanted to go backwards and list the years in reverse order. Try this:
<% FOR intYearCounter = (intCurrentYear + 7) TO
intCurrentYear STEP -1 %>
In the example above we will run our loop backwards in a sense. We will start with a larger number and STEP backwards by -1 until we get to the smallest number.
Feel free to take the code above and play around with it using STEP and changing the numbers. Be careful not to get yourself stuck in an infinite loop, though. Make sure your loops will have a predictable beginning and ending.
|Cutting and Pasting Code
Because of our limited column space we often have to break single lines of code into multiple lines. If you choose to cut and paste the code be sure to remove any line breaks. In order for ASP to interpret your code correctly, each line of code beginning with <% and ending with %> MUST be on a single line. We will demonstrate how to break up lines of code later in this series.
back to top
The DO .. LOOP is a combination of the IF .. THEN statement and the FOR .. NEXT loop. It's a conditional loop. In other words, it loops repeatedly (like a FOR .. NEXT loop) until some specific criteria is met (like an IF .. THEN statement).
Here is a basic example of the DO .. LOOP:
<% DIM intDice, intRollCounter %>
<% intRollCounter = 0 %>
<% Randomize %>
<% DO UNTIL intDice = 6 %>
<% intRollCounter = intRollCounter + 1 %>
<% intDice = Int(Rnd * 6) + 1 %>
<% LOOP %>
<% Response.Write "It took " & CStr(intDice)
& " tries to roll a 6!" %>
This example is a simple dice game. We will keep automatically rolling a single die until we get a six and then output how many tries it took. Let's walk through the code.
The first new thing that you will encounter is the Randomize command. This command simply sets a random number seed so that you can generate random numbers. We'll cover both Randomize and Rnd in more detail later in this series.
After Randomize comes the DO statement. Like FOR, this simply tells the server that we are beginning our loop here. Then comes UNTIL. UNTIL is the conditional part and works just as you would expect it to. Each time through the loop it checks to see if our criteria is met, i.e. intDice = 6. When it does equal 6 the loop stops executing.
Next you will see intRollCounter be incremented by one each time we go through the loop. We are doing our incrementing by hand this time instead of using a FOR .. NEXT loop because we don't know how many times the loop will execute before intDice equals 6.
Then we generate a random number between 1 and 6. We'll talk about how this works when we cover Randomize and Rnd later in this series.
The last part of our loop is designated by, you guessed it, LOOP. This tells the server that we have reached the bottom of the loop and to try it again UNTIL we get it right.
Lastly, after our loop is done looping we simply write a line that says how many times we had to loop through to get a 6.
There's also another way to approach this. We could use WHILE instead. WHILE is the polar opposite of UNTIL. WHILE keeps going until a condition is not met. Let's change the DO line to use WHILE instead:
<% DO WHILE intDice <> 6 %>
We are accomplishing the same task as before but we are just wording it a bit different. Now we are saying keep looping as long as intDice does not equal 6.
Obviously, each situation will logically lend itself to either WHILE or UNTIL. You'll have to determine for yourself which makes your code easier to read and more intuitive. In our case UNTIL makes the most sense.
Now, there's one other little twist you will need to know. WHILE and UNTIL can be used either at the top or the bottom of the loop. That means we could move the UNTIL in our example down to the bottom of the loop like this:
<% LOOP UNTIL intDice = 6 %>
Now instead of doing our test at the top of the loop we are doing it at the bottom. I know it doesn't sound like a big deal but it can be very important. If you place UNTIL or WHILE at the bottom you are ensured that your loop will execute at least one time. If you put them at the top, your loop may never execute if your condition is already met when the loop begins. This can be a very important distinction depending on your circumstance.
back to top
And now for a new way to store information .. arrays. Arrays are a very handy storage method. Think of arrays as variables on steroids.
Imagine you wanted to store 20 different people's last names in variables. It would be quite a pain to create and keep track of strLastName1, strLastName2, etc. Not very efficient, right? That's where arrays come in. With an array you can create one variable that will have 20 slots, one for each person's name. Here is how you would declare that array:
<% DIM strLastNames(20) %>
Now you have a variable ready to receive your twenty names. Think of it as a table with 1 column and 20 rows. To refer to each slot in your array simply refer to its index number like this:
<% strLastNames(1) = "Smith" %>
<% strLastNames(2) = "Hatfield" %>
For an example of how arrays can be used let's go back to our FOR .. NEXT example. Change the DIM statement to this:
<% DIM intYearArray(8), intYearCounter,
Now you have an array to store the years that you will generate in the FOR .. NEXT loop. Add this line inside the FOR .. NEXT loop:
<% intYearArray (intYearCounter - intCurrentYear + 1)
= intYearCounter %>
While that looks incredibly complicated, it's not. Since our loop doesn't count from 1 to 8 we have to reduce our year counter down to single index numbers 1 through 8. That's what our little formula inside the parentheses does.
Now, if you want to get a bit more complicated you can use a two dimensional array. Think of this as a table with x number of rows and y number of columns. Here is how you would declare a two dimensional array:
<% DIM strMyArray(20,10) %>
Think of strMyArray as a "table" that is 20 rows by 10 columns. With a two dimensional array it is a bit more complicated to keep track of your index numbers for each item. However, if you imagine your data in a table and you remember that strMyArray(1,1) is the top left corner then it shouldn't be too difficult. If you really want to get complicated you could go for the three dimensional effect like this:
<% DIM strMyArray(5,5,5) %>
Now you more or less have a cube that is 5 blocks wide by 5 blocks tall by 5 blocks deep.
So, what about getting stuff back out of an array? That's pretty easy actually. All you need to do is refer to the index number of the item that you want to retrieve. If we wanted to get an item out of our intYearArray we would just refer to an index number like this:
intTheLastYear = intYearArray(8)
In a two dimensional array like this:
strData = strMyArray(7,2)
You get the idea. But if you wanted to get the data out of each element of your array you could save yourself some time by using a specialized FOR .. NEXT loop like this:
<% DIM intEachYear %>
<% FOR EACH intEachYear IN intYearArray %>
<% Response.Write intEachYear %>
<% NEXT %>
You'll notice we defined our FOR very differently. Here we are telling the server to loop through EACH element in intYearArray (from the example above). Each time through the loop we want the current element to be temporarily placed in the variable intEachYear. Then within the loop we will simply print out each element as it loops through. What we will end up with is our series of years all printed on the same line.
back to top
We're getting somewhere now! Next it's on to some of the different functions of VBScript and ASP. These little guys will do a lot of your programming work for you. Learn them well.
In the next part of this series we will:
Do the Math Functions
Messing with String Functions
Nailing Down the Date & Time Functions