无法循环c#中的所有控件

Bìn*_*yên 3 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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?

GSe*_*erg 8

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

您应该重写此内容,首先构建一个需要重新构建的控件列表,然后在第二次传递中重新显示它们.