Looping Constructs: for, while, and foreach in C# WinForms

Repeat tasks efficiently in your WinForms apps

Loops let you perform actions multiple times β€” like processing a list, generating rows, or updating UI elements in bulk. Instead of repeating code manually, you use a loop to do the work for you.

Let’s explore how to use the three most common C# loops: for, while, and foreach.


🧱 When to Use Loops in WinForms

  • Generating lists of data
  • Populating UI controls (ListBox, ComboBox)
  • Processing multiple inputs
  • Performing repetitive calculations
  • Searching through collections

πŸ”’ for Loop – Count-Controlled Repeats

Use when you know how many times to loop.

for (int i = 0; i < 5; i++)
{
    listBox1.Items.Add("Item " + i);
}

πŸ’‘ Useful for indexed loops or generating numbered items.


πŸ” while Loop – Condition-Controlled Repeats

Use when you don’t know how many times, but want to keep going while a condition is true.

int count = 0;
while (count < 5)
{
    listBox1.Items.Add("Count is: " + count);
    count++;
}

πŸ’‘ Be careful! while loops can become infinite if the condition never becomes false.


πŸ”„ foreach Loop – Iterate Over Collections

Use to go through each item in a list or array.

string[] fruits = { "Apple", "Banana", "Cherry" };

foreach (string fruit in fruits)
{
    listBox1.Items.Add(fruit);
}

βœ… Clean and safe β€” no need to track index manually.


πŸ“‹ Example: Display List of Names

private void btnShowNames_Click(object sender, EventArgs e)
{
    string[] names = { "Alice", "Ben", "Clara", "David" };

    listBox1.Items.Clear();

    foreach (string name in names)
    {
        listBox1.Items.Add("Hello, " + name + "!");
    }
}

πŸ§ͺ Example: Show Multiplication Table

private void btnTable_Click(object sender, EventArgs e)
{
    int number = int.Parse(txtNumber.Text);
    listBox1.Items.Clear();

    for (int i = 1; i <= 10; i++)
    {
        listBox1.Items.Add($"{number} x {i} = {number * i}");
    }
}

βœ… Dynamic output based on user input β€” powerful and reusable.


🧠 Which Loop Should I Use?

Loop TypeBest When…
forYou know how many times to run
whileYou run until something happens
foreachYou’re working with a collection (e.g., array)

🚫 Common Mistakes

  • ❌ Forgetting to increment (count++) in while or for
  • ❌ Looping over null collections
  • ❌ Infinite loops: while (true) with no exit
  • ❌ Modifying a collection while looping through it with foreach

πŸ§ͺ Quick Challenge

🧩 Build a form that:

  • Accepts a number input
  • Displays a list of square numbers from 1 to N
  • Uses a for loop to calculate and a ListBox to show results

Bonus: Add a foreach loop that reads an array of favorite colors and displays each in a Label or ListBox.


πŸ“š Summary

KeywordPurpose
forRepeat with counter/index
whileRepeat while a condition is true
foreachLoop through items in a collection

βœ… Best Practices

  • βœ… Clear ListBox.Items before adding new results
  • βœ… Use foreach when possible for cleaner syntax
  • βœ… Always ensure your loop has a safe exit condition
  • βœ… Use meaningful loop variable names (index, i, item)

πŸŽ“ Want to Go Further?

  • Use break and continue inside loops
  • Nest loops to generate grids or tables
  • Dynamically create controls in loops (e.g., buttons in a row)
  • Combine loops with if for filtered outputs

πŸ’¬ Need help building a form that loops through items or generates output dynamically?
Just describe the idea β€” We’ll help you wire up the logic with the right loop!