Reputation: 91
As in the title, my question is how does C# iterate through form controls in a foreach
loop? In case that is a bit too vague I'll add a bit more detail:
When I do foreach(Control c in MyForm)
how does it index(?) through the controls? Is it based on tab order or something else? Any assistance would be appreciated as I'm trying to find out if I can place values into an array in a neater and more organized fashion.
Upvotes: 1
Views: 1752
Reputation: 4672
Are you referring to the order that the controls are iterated over? I want to say that the controls are iterated over in the order that they were added to the Form's control collection. You can check this in the InitializeComponents
designer method to see the order the controls are listed in that method.
Upvotes: 0
Reputation: 125342
It doesn't return controls based on tab index, it returns the controls in the order you added them the Controls
collection.
You can see this order in designer in Document Outline window. (Ctrl + Alt + T) and change the order by moving controls in tree in the Document Outline window. Also if you use Bring To front
and Send To back
toolbar buttons you can change this order in design time.
At run-time you can change this order by calling SendToBack
and BringToFront
method of controls or SetChildIndex
method of Controls
collection.
To get the index of a control, you can use GetChildIndex
method of Controls
collection.
Also keep in mind foreach(Control c in this.Controls)
just will scan controls which you put directly on the form. For example if you have a panel on form and the panel contains some controls, children of panel are in panel.Controls
collection and not in controls collection of form.
Upvotes: 3
Reputation: 61379
foreach
always works the same, so doing it over a form's controls doesn't change anything.
It doesn't really use an index either; foreach
only works on instances of classes that implement IEnumerable
which means they have a GetEnumerator
method. foreach
uses the returned IEnumerator
to go through the collection one at a time; order is dependent on the actual implementation.
For List
(or any array) this is in-order (ie index 0 is first, 1 second, and so on); for a random implementation of IEnumerable
you would have to look at the source. In your specific example, look at the type of the Controls
collection on Form
. Its a ControlCollection
so you'll want to look on Reference Source to find how it enumerates.
Based on the implementation it appears to be in-order with some safeguards against controls being removed during enumeration.
Upvotes: 4