Enumerating Controls on a Form

谁都会走 提交于 2019-12-11 00:32:13

问题


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?


回答1:


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))
{
}



回答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.



来源:https://stackoverflow.com/questions/5265903/enumerating-controls-on-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!