Reputation: 76
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!
Upvotes: 0
Views: 329
Reputation: 30052
You can query that using Linq:
this.Controls.OfType<GroupbBox>().Where(x=> x.Name == "SomeName").ToList();
Upvotes: 1
Reputation: 43936
Well to find all groupboxes there is no better way than to iterate over all of them. But (for me) the code would look better with this:
List<GroupBox> gBoxes = this.Controls.OfType<GroupbBox>().ToList();
OfType<T>
selects all elements of a sequence that are of that type.
Note that this only finds all groupboxes directly contained in this ControlCollection
but not in sub-containers. You may want to collect the groupboxes recursively:
public IEnumerable<GroupBoxes> GetAllGroupBoxes(Control c)
{
return c.Controls.OfType<GroupBox>()
.Concat(c.Controls.OfType<Control>().SelectMany(GetAllGroupBoxes));
}
List<GroupBox> gBoxes = GetAllGroupBoxes(this).ToList();
To filter for a specific name you can use Where
:
Controls.OfType<GroupBox>().Where(gb => gb.Name == "whatever")...
Upvotes: 1