AllTheTimeWorld.com

csharp loopsFor Each Loops with a List

For Each Loops with a List

Use the foreach loop to remove blank lines from a list box.

For Each Loops with a List

Use the foreach loop to remove blank lines from a list box.


Text of video

The foreach loop works on a collection, array, or list.
All of the items in a listbox can be inspected with a foreach loop.
Note: we can't remove an item in the foreach loop, becaseu that would change the list of items.

private void Form1_Load(object sender, EventArgs e)
{
   int blank = 0;
   //Count the number of blanks in the list box
   foreach(String s in listBox1.Items)
   {
      if (s == "") blank++;
   }
   this.Text = "You had " + blank + " blank lines";
   //Remove all of the blank lines
   for (int i = 0; i < blank; i++)
   {
      this.listBox1.Items.Remove("");
   }
}