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 Type | Best When⦠|
|---|---|
for | You know how many times to run |
while | You run until something happens |
foreach | Youβre working with a collection (e.g., array) |
π« Common Mistakes
- β Forgetting to increment (
count++) inwhileorfor - β Looping over
nullcollections - β 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
forloop to calculate and aListBoxto show results
Bonus: Add a foreach loop that reads an array of favorite colors and displays each in a Label or ListBox.
π Summary
| Keyword | Purpose |
|---|---|
for | Repeat with counter/index |
while | Repeat while a condition is true |
foreach | Loop through items in a collection |
β Best Practices
- β
Clear
ListBox.Itemsbefore adding new results - β
Use
foreachwhen 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
breakandcontinueinside loops - Nest loops to generate grids or tables
- Dynamically create controls in loops (e.g., buttons in a row)
- Combine loops with
iffor 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!