kodkod
kodkod

Reputation: 1576

foreach loop over TextBoxes in GroupBox iterates in reverse order?

I created four TextBoxes (in this order: textBox1, textBox2,...) and put them one below the other inside a GroupBox. Then I added the Click event:

private void button1_Click(object sender, EventArgs e)
{
    foreach (TextBox tb in groupBox1.Controls.OfType<TextBox>())
    {
        if (string.IsNullOrWhiteSpace(tb.Text))
        {
            Console.WriteLine(tb.Name);
        }
    }
}

When I run the program and click the Button (when all the TextBoxes are empty), this is the output I get:

textBox4

textBox3

textBox2

textBox1

Apparently the foreach loop iterated over the GroupBox controls in reverse order. I expected it to do it from textBox1 to textBox4 because this was the order they were created and put in the groupbox.

Why did the foreach loop in reverse? Just curious...

Upvotes: 2

Views: 2176

Answers (2)

Jitendra.Suthar
Jitendra.Suthar

Reputation: 110

Try this

foreach (TextBox txt in Controls.OfType<GroupBox>().SelectMany(g=>g.Controls.OfType<TextBox>()).ToList().Reverse<TextBox>())
        {
            //Write your logic here
        }

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460118

The controls are placed in order of the Z-order of the controls in the same parent container (top-most to bottom-most). How do you want to order them?

Upvotes: 5

Related Questions