For Each Loops
The foreach loop works on a collection or an array.
For Each Loops
The foreach loop works on a collection or an array.
Text of videoThe foreach loop works on a collection or an array.
All of the controls on a form makeup a collection.
The foreach loop can be used to loop through each object in a collection.
Start a new application and place a few controls of various types on the form.
Write the code in Form Load:
private void Form1_Load(object sender, EventArgs e)
{
// Change the backcolor of each control on the form to red.
foreach (Control ctrl in this.Controls)
{
// ctrl is assigned one control at a time
ctrl.BackColor = Color.Red;
//Change text of control
if (ctrl.GetType() == typeof(Button))
ctrl.Text = "CLICK HERE!";
else ctrl.Text = ctrl.GetType().ToString();
}
}