Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't loop all controls in c#

Tags:

c#

winforms

I have a C# form with some types of controls, i throught this code for loop all Labels and re-parent:

private void MakeAllLabelTrans(Control frm, Control parent)
{
    foreach (Control ctl in frm.Controls)
    {
        if (ctl is Label)
        {
            ctl.Parent = parent;
            // ctl.BackColor = Color.Transparent;
        }
        else if (ctl.HasChildren)
        {
            MakeAllLabelTrans(ctl, parent);
        }
    }
}

and call as: MakeAllLabelTrans(this, picBackground); in Form_Load event, but some label was missed (i have puted a messagebox in the loop body - it really not in the loop), but i don't know why?

like image 907
Bình Nguyên Avatar asked May 30 '26 01:05

Bình Nguyên


2 Answers

You're changing the collection while enumerating it. This leads to some items being skipped.

You should rewrite this to first build a list of controls that will need to be reparented, and then reparent them in a second pass.

like image 197
GSerg Avatar answered May 31 '26 15:05

GSerg


You should not modify the collection on which you are iterating.

private static IEnumerable<Labels> FindAllLabels(Control container)
{
    foreach (Control ctl in container.Controls)
    {
        var lbl = ctl as Label;
        if (lbl != null)
        {
            yield return ctl;
        }
        else if (ctl.HasChildren)
        {
            foreach (var innerResult in FindAllLabels(ctl))
                yield return innerResult;
        }
    }
}

// now call the method like this if you want to change a property on the label
foreach (var label in FindAllLabels(theForm))
    label.BackgroundColor = Color.White;

// or like this (note the .ToList()) if you want to move the labels around:
foreach (var label in FindAllLabels(theForm).ToList())
    label.Parent = someOtherControl;
like image 21
Knaģis Avatar answered May 31 '26 13:05

Knaģis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!