I have a bit of code which loops through my groupBox controls and fetches the name of the control. It then writes the names into a textbox. However, the order in which they are looped through needs to be in line with the names, gb1, gb2, gb3... The order by which they are looped through right now appears to be the order in which they were created (time wise). I have tidied up the designer code so creation of the controls is ordered in the way I want it, but it appears to make no difference. Any pointers? Thanks
private void loopThroughControls()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl.ToString().StartsWith("System.Windows.Forms.GroupBox"))
{
txtEntry.Text += (ctrl.Text + System.Environment.NewLine);
}
}
}
To expand on Tomas' answer:
private void LoopThroughControls()
{
foreach (var ctrl in this.Controls.OfType<GroupBox>().OrderBy(c => c.Name))
{
txtEntry.Text += (ctrl.Text + System.Environment.NewLine);
}
}
This will retrieve the GroupBox
instances from the Controls
collection, then it sorts them by their name, and then it gets the text content like you wanted.