I created four TextBox
es (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 TextBox
es 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...
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?
Try this
foreach (TextBox txt in Controls.OfType<GroupBox>().SelectMany(g=>g.Controls.OfType<TextBox>()).ToList().Reverse<TextBox>())
{
//Write your logic here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.