TutorialsRoom.com
RSS Feed

Subscribe: RSS or e-mail

Home » Web Development » ASP.NET »

ASP.Net for and foreach Loops

ASP.Net for and foreach Loops
In this ASP.Net C# tutorial, we will learn about two of the most common C# loops: ASP.Net C# for loop and ASP.Net C# foreach loop. Almost any program that you will write will have at least one of those two loops.

We will start by adding numbers from one to ten in a ListBox using the for loop. So open your Visual Studio and add a ListBox, name it lstFor and also drop a button and name it btnExecute.

Double click on the btnExecute button and type for then press the Tab key twice to invoke the code snippet for the for loop and you will get this nice code:

  for (int i = 0; i < length; i++)
  {
   
  }

C# for loop consists of three parts separated by semicolons (;), we initialize a variable that we will use in our for loop in the first part, in the second part we type a Boolean expression which for loop will continue looping as long as this condition is true and finally how we will change the value of our variable after each time the for loop loops. Notice that all the parts of the for statement are optional.

Change your code like that for the purpose of our tutorial:

  for (int i = 1; i < 11; i++)
  {
  
  }

The above code means we will start to give the variable i the initial value of 1, we will loop as long as i is less than 11 and the i++ is well known for the C programmers and it means add one to the value of i. The great thing about the ASP.Net for loop in C# is that all the control keywords of the for loop statement are in one line, so it's really simple and clear.

Now we will make use if a nice ASP.Net control, the ASP.Net ListBox by modifying our code like the following:

  lstFor.Items.Clear();
  for (int i = 1; i < 11; i++)
  {
      lstFor.Items.Add(i.ToString());
  }

Most of the time when we use the ASP.Net ListBox control we will actually use the Items collection of the ASP.Net ListBox, first we will clear its items or otherwise we will get another group of ten numbers every time the user clicks the button, then we add the value of the i variable (after converting it from integer to string) to the ListBox every time the for loop iterates. The code is simple, clear and sufficient and that's what I love about the for loop! Your result should look something like that:

ASP.Net for Loop

Another great loop is the ASP.Net foreach loop which is slightly different from the previous for loop, it will iterate though all the items in a collection, it's very useful too, so let's learn about the ASP.Net foreach statement.

Type foreach and press the Tab key twice, don't you love the Visual Studio Code Snippets? I know I do!

  foreach (var item in collection)
  {
      
  }

The code snippet tells you exactly what I was saying. The green areas in the code snippet defines the places that you would generally change, you can move back and forth using the Tab key and get inside the foreach loop block by pressing the Enter key, really useful.

We will check if a number is odd or even in our code so add another ListBox and name it lstForeach, now, we will iterate though all the items in the previous lstFor ListBox and add only the even numbers in the other lstForeach ListBox and here is the code we will add:

  lstForeach.Items.Clear();
  foreach (ListItem item in lstFor.Items)
  {
      if (int.Parse(item.Value) % 2 ==  0 )
      {
          lstForeach.Items.Add(item);
      }
  }

First we clear the Items collection of the second lstForeach ListBox then we start our foreach loop by declaring a variable called item of type ListItem because this is the type of the lstFor.Items collection items then we make a use of the C# modulus operator (%) which returns the remainder when dividing two numbers, this is always 0 for even numbers and 1 for odd numbers and finally, add the item directly to the lstForeach ListBox. Here is the full code:

  lstFor.Items.Clear();
  //for loop
  for (int i = 1; i < 11; i++)
  {
      lstFor.Items.Add(i.ToString());
  }
  
  lstForeach.Items.Clear();
  //foreach loop
  foreach (ListItem item in lstFor.Items)
  {

      if (int.Parse(item.Value)%2 == 0 )
      {
          lstForeach.Items.Add(item);
      }
  }

Nice and simple, right? Your result should look something like that:

ASP.Net foreach Loop

What if we want to skip some iterations based on an expression? Here comes the continue keyword so for example, if we for some reason want to skip adding the number two to the lstForeach ListBox, here is what we will be writing:

  lstForeach.Items.Clear();
  foreach (ListItem item in lstFor.Items)
  {

      if (int.Parse(item.Value)%2 == 0 )
      {
          if (item.Value == "2")
          {
              continue;
          }
          lstForeach.Items.Add(item);
      }
  }

You can also exit the foreach loop completely anytime using the break keyword. Also notice, if you try to modify the collection that you are iterating though in the foreach loop, you will get an error: Collection was modified; enumeration operation may not execute.

Rating: 2.9/5 (126 Votes)
Copyright © 2007-2014 Hazem Osman. All rights reserved. Terms & Conditions