Fancy_Mammoth Fancy_Mammoth - 18 days ago 7
C# Question

How does C# iterate through Form Controls in a Foreach loop

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.

Answer

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.

Comments