Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

Tags:

c#

winforms

How can I use a Foreach Statement to do something to my TextBoxes?

foreach (Control X in this.Controls)
{
    Check if the controls is a TextBox, if it is delete it's .Text letters.
}
like image 594
Sergio Tapia Avatar asked Sep 30 '09 15:09

Sergio Tapia


3 Answers

If you are using C# 3.0 or higher you can do the following

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
  ..
}

Without C# 3.0 you can do the following

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {
    ...
  }
}

Or even better, write OfType in C# 2.0.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;
    }
  }
}

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
  ..
}
like image 119
JaredPar Avatar answered Nov 11 '22 16:11

JaredPar


You're looking for

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
  }
}
like image 28
JustLoren Avatar answered Nov 11 '22 16:11

JustLoren


The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.

I recommend using an extension of Control that will return something more..queriyable ;)

public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }

Then you can do :

foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
    // Apply logic to the textbox here
}
like image 8
Mathlec Avatar answered Nov 11 '22 15:11

Mathlec