Search code examples
c#winformsgroupbox

Excluding the GroupBoxes that are inside another GroupBox


Let's say I have 7 group boxes but some of them also have group box inside them and some do not. now if I want to iterate through those 7 group boxes and apply something to them, is there a way that I can exclude those Child group boxes from this loop?


Solution

  • though i question the choice of implementation (can you use polymorphism instead? what exactly are you trying to do?), there is a Parent property, e.g.

    void soSomething(Control ctrl)
    {
        if (ctrl is GroupBox && (ctrl.Parent is null || !(ctrl.Parent is GroupBox)))
        {
             //do something here
        }
        foreach(Control child in ctrl.Controls)
        {
            doSomething(child);
        }
    }