anon271334
anon271334

Reputation:

Enumerating Controls on a Form

I have a form with about 30 controls on it, and when the user clicks a button, data from each control is saved to a file. But I need to go through every single control on the form (which I can do), but it needs to be in order, For example, I need to start right at the top left of the form and work my way down to the bottom right of the form.

Is this how a foreach loop would work? I.e.:

foreach(Control control in this.Controls)
{
}

Or does it not go through them in order?

Upvotes: 2

Views: 2104

Answers (2)

Do you need to enumerate the child-controls of your controls as well?

If not, try

foreach(Control control in this.Controls.Cast<Control>().OrderBy(o => o.Location.Y).ThenBy(o => o.Location.X)
{
    ...
}

This will enumerate the controls, beginning in the upper-left and moving right, then down.

Upvotes: 2

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

That would return the controls in the order they are added to the form, not in visual order.

If you have set up your TabIndex in the same order as you want to parse the controls you can use LINQ to sort them by TabIndex.

foreach (Control control in this.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
{
}

Upvotes: 4

Related Questions