Search code examples
c#winformscontrolsgroupbox

Get only the groupBoxes from a winform


i made this code for get all the groupboxes from a winform and then take only the ones with a determinated name.

Control.ControlCollection controles = this.Controls;   
GroupBox gBoxAux = new GroupBox();             
List<GroupBox> gBoxes = new List<GroupBox>();

foreach (Control c in controles)
{                                        
   if (c.GetType() == typeof(GroupBox))
   {
       gBoxAux = (GroupBox)c;
       gBoxes.Add(gBoxAux);                        
   }
}

I don't know if there's a better way to do it instead of iterate over all the controls.

Thank you very much!


Solution

  • You can query that using Linq:

    this.Controls.OfType<GroupbBox>().Where(x=> x.Name == "SomeName").ToList();