Well, I have this code, it works properly if I use for loop over foreach loop. I try to change background and foreground colors for all Labels on form using foreach to process every control. In foreach I've made a condition that determines if control in current iteration is Label and if that's true it will change color.
The problem is foreach runs over every Control on form but if I add condition and any action in it, this foreach will count 22 Labels on form but I have 44 labels over the picturebox.
If I add for loop or while loop, it will start foreach many times and all Labels will be painted. Is that right way to paint all Labels using loops? See the code below:
/// <summary>
/// Changes background color of each label on form
/// to transparent and foreground color to white.
/// </summary>
public void PaintLabels()
{
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
{
c.Parent = Map;
c.BackColor = Color.Transparent;
c.ForeColor = Color.White;
}
}
}
The problem is if I don't add for
loop around that foreach
, this code will work only with 22 Labels on form though condition doesn't say about that. So I need to use for
loop with counter from 0 to 6 to force this code to work correctly, but I think that's bad practice and want to find correct solution for this task. Why that foreach
does not pick all child items on a single iteration?
Standalone MRE for LinqPad (or just console app)
var control = new Form();
var group = new GroupBox();
control.Controls.Add(group);
var Map = new GroupBox();
control.Controls.Add(Map);
foreach (var element in Enumerable.Range(0, 10))
{
group.Controls.Add(new Label() { Text = element.ToString() });
}
foreach (Control c in group.Controls)
{
c.Parent = Map;
Console.WriteLine(c.Text); // 0 2 4 8 instead of 0 1 2 ... 9
}