简体   繁体   中英

C# Looping through textboxes in a GroupBox

I have a few textboxes inside a groupbox, I want to loop through them and add strings from List (array).

I've tried that:

foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox1 => groupBox1.Controls.OfType<TextBox>()))
                   {
                       textBox.Text = List[counter];
                       counter++;
                   } 

But it doesn't work for me, nothing happens.

Here's a way: It assumes there is more than one type of control in the group box. If there are only textboxes, you can simplify it.

private void button1_Click(object sender, EventArgs e)
{
    int Counter = 0;

    foreach (Control control in groupBox1.Controls)
    {
        TextBox textBox = control as TextBox;

        if (textBox != null)
            textBox.Text = Counter++.ToString();   
    }
}

Try this

foreach(var groupBox in Controls.OfType<GroupBox>()) {
     foreach(var textBox in groupBox.Controls.OfType<TextBox>()) { 
    // Do Something 
    } 
}

Can you try this one.

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

A cleaner approach is

foreach(Control control in groupBox1.Controls)
{
    // Check if the object is indeed what we need
    if(!(control is TextBox))
        continue;

    // "Cast" the object to a TextBox
    TextBox textBox = control as TextBox;

    // Do your thing with the textboxes
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM