Tom S
Tom S

Reputation: 551

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.

Upvotes: 0

Views: 5412

Answers (4)

davidanderle
davidanderle

Reputation: 668

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
}

Upvotes: 0

Jitendra.Suthar
Jitendra.Suthar

Reputation: 110

Can you try this one.

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

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20620

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();   
    }
}

Upvotes: 2

Yogesh Patel
Yogesh Patel

Reputation: 712

Try this

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

Upvotes: 1

Related Questions