Article

ASP.NET 2.0: A Getting Started Guide

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Next

Loops

As you've just seen, an If statement causes a code block to execute once if the value of its test expression is true. Loops, on the other hand, cause a code block to execute repeatedly for as long as the test expression remains true. There are two basic kinds of loop:

  • While loops, also called Do loops (which sounds like something Betty Boop might say!)
  • For loops, including For Next and For Each

A While loop is the simplest form of loop; it makes a block of code repeat for as long as a particular condition is true. Here's an example:

Example 3.16. Loops.aspx          
         
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"          
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">          
<html>          
 <head>          
   <title>Loops</title>          
   <script runat="server" language="VB">          
     Sub Page_Load(s As Object, e As EventArgs)          
       ' Initialize counter          
       Dim counter As Integer = 0          
       ' Loop          
       Do While counter <= 10          
         ' Update the label          
         messageLabel.Text = counter.ToString()          
         ' We use the += operator to increase our variable by 1          
         counter += 1          
       Loop          
     End Sub          
   </script>          
 </head>          
 <body>          
   <form runat="server">          
     <asp:Label id="messageLabel" runat="server" />          
   </form>          
 </body>          
</html>          
         
Example 3.17. Loops.aspx          
         
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"          
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">          
<html>          
 <head>          
   <title>Loops</title>          
   <script runat="server" language="C#">          
     void Page_Load()          
     {          
       // initialize counter          
       int counter = 0;          
       // loop          
       while (counter <= 10)          
       {          
         // Update the label          
         messageLabel.Text = counter.ToString();          
         // C# has the ++ operator to increase a variable by 1          
         counter++;          
       }          
     }          
   </script>          
 </head>          
 <body>          
   <form runat="server">          
     <asp:Label id="messageLabel" runat="server"/>          
   </form>          
 </body>          
</html>

If you load this page, you'll get the result illustrated in Figure 3.5.

1556_0325_Loops
Figure 3.5. Results of a While loop

When you open the page, the label will be set to show the number 0, then 1, then 2, all the way to 10. Of course, since all this happens in Page_Load (i.e. before any output is sent to the browser), you'll only see the last value assigned: 10.

This demonstrates that the loop repeats until the condition is no longer met. Try changing the code so that the counter variable is initialized to 20 instead of 0. When you open the page now, you won't see anything on the screen, because the loop condition was never met.

The other form of the While loop, called a Do While loop, checks whether or not the condition has been met at the end of the code block, rather than at the beginning:

Example 3.18. Loops.aspx (excerpt)          
         
Sub Page_Load(s As Object, e As EventArgs)          
 ' Initialize counter          
 Dim counter As Integer = 0          
 ' Loop          
 Do          
   ' Update the label          
   messageLabel.Text = counter.ToString()          
   ' We use the += operator to increase our variable by 1          
   counter += 1          
 Loop While counter <= 10          
End Sub          
         
Example 3.19. Loops.aspx (excerpt)          
         
void Page_Load()          
{          
 // initialize counter          
 int counter = 0;          
 // loop          
 do          
 {          
   // Update the label          
   messageLabel.Text = counter.ToString();          
   // C# has the operator ++ to increase a variable by 1          
   counter++;          
 }          
 while (counter <= 10);          
}

If you run this code, you'll see it provides the exact same output we saw when we tested the condition before the code block. However, we can see the crucial difference if we change the code so that the counter variable is initialized to 20. In this case, we will, in fact, see 20 displayed, because the loop code is executed once before the condition is even checked! There are some instances when this is just what we want, so being able to place the condition at the end of the loop can be very handy.

A For loop is similar to a While loop, but we typically use it when we know beforehand how many times we need it to execute. The following example displays the count of items within a DropDownList control called productList:

Dim i As Integer          
For i = 1 To productList.Items.Count          
 messageLabel.Text = i.ToString()          
Next          
         
int i;          
for (i = 1; i <= productList.Items.Count; i++)          
{          
 messageLabel.Text = i.ToString();          
}

In VB, the loop syntax specifies the starting and ending values for our counter variable within the For statement itself.

In C#, we assign a starting value (i = 1) along with a condition that will be tested each time we move through the loop (i <= productList.Items.Count), and identify how the counter variable should be incremented after each loop (i++). While this allows for some powerful variations on the theme in our C# code, it can be confusing at first. In VB, the syntax is considerably simpler, but it can be a bit limiting in exceptional cases.

The other type of For loop is For Each, which loops through every item within a collection. The following example loops through an array called arrayName:

For Each item In arrayName          
 messageLabel.Text = item          
Next          
         
foreach (string item in arrayName)          
{          
 messageLabel.Text = item;          
}

You may also come across instances in which you need to exit a loop prematurely. In these cases, you would use either Exit, if your code is in VB, or the equivalent (break) statement in C#, to terminate the loop:

Dim i As Integer          
For i = 0 To 10          
 If (i = 5) Then          
   Response.Write("Oh no! Not the number 5!!")          
   Exit For          
 End If          
Next          
         
int i;          
for (i = 0; i <= 10; i++)          
{          
 if (i == 5)          
 {          
   Response.Write("Oh no! Not the number 5!!");          
   break;          
 }          
}

In this case, as soon as our For loop hits the condition i = 5, it displays a warning message using the Response.Write method (which will be familiar to those with past ASP experience), and exits the loop so that no further passes through the loop will be made.

Although we've only scratched the surface, VB and C# provide a great deal of power and flexibility to web developers, and time spent learning the basics now will more than pay off in the future.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links