How to change the font color of a textbox in c#.net if I move the textbox in a groupBox?

How to change the font color of a textbox in c#.net if I move the textbox in a groupBox? It works when there is no groupbox, but if textbox is in a group box the font color is not changing.

This is the initial code that worked before entering the groupbox.

foreach (object t in this.Controls)
  if (t.GetType() == typeof(TextBox))
      ((TextBox)t).BackColor = Color.AntiqueWhite;

Upvotes: 1

Views: 997

Answers (1)

Chris
Chris

Reputation: 5514

When you loop on this.Controls you're just getting that level of controls, i.e. the controls that are direct children of (what I would assume to be) your form.

Try:

foreach (object t in groupBox1.Controls)
        if (t.GetType() == typeof(TextBox))
            ((TextBox)t).BackColor = Color.AntiqueWhite;

If you need to find all textboxes on the entire form, write a recursive function to go through the entire control tree:

private void ForAll<T>( Control c, Action<T> func ) where T : Control
{
    if( c is T )
        func( (T)c );
    foreach( Control child in c.Controls )
        ForAll( child, func );
}

And use like:

ForAll<TextBox>( this, c => c.BackColor = Color.AntiqueWhite );

Upvotes: 2

Related Questions