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开发者_如何学JAVA 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?
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))
{
}
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.
精彩评论