It is a very basic, but somewhat confusing for the beginner loop. For might be familiar with the for loop,
for (int i = 0; i < 10; i++) {
Console.WriteLine(i);
}
.. this does the same, but has a different logic and syntax. Let me first make you understand the very basic of this loop's syntax.
foreach (datatype identifier in collection) {
}
datatype
is the type of the data that we're going to work. In the above case it was
int
, identifier is the variable name that we're going to call the element in the list as, in the above case it was i. After that, in the above code there was a condition, in this we don't have a condition. Foreach loop creates a condition on itself, and we just have to worry about the elements.
collection
contains the list of the element. It can be an array, an enumeration or list etc. But must be able to contain elements.
I hope you're understanding the syntax, so now lets get to the code you're having.
foreach (Control txt in this.Controls) {
if (txt is TextBox) {
txt.Text = "something";
}
}
This was the code you were having, and you can see now, it is trying to access every object that is of
Control
type and then is naming it as txt. Where actually is it finding them? It is finding them inside the current context's Controls. Controls is some object inside the current class (being referenced by
this
and then calling the Controls object).
This loop would execute for each of the Control (txt is just a name that we're giving to it, it is not specified inside the class) and then it is checking the condition, that whether this Control is a TextBox (editable textarea) Control. If it is, then it is editting the value of it, to be "something".
Lets take one more look at the code now,
foreach (Control txt in this.Controls) {
if (txt is TextBox) {
txt.Text="something";
}
}
I hope you got the point of the iteration. Now, the order thing? That is because the Collection you're working on is not ordered, try something like
Controls = Controls.OrderBy(r => r.Id)
This will order the controls by their ID (I wonder if they even have one; use your own values). This part must be went through first and then the iteration would come up to work with the ordered collection.
Good luck!