简体   繁体   中英

Can't loop all controls in c#

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM