28

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.
}
Nathan Koop
  • 24,803
  • 25
  • 90
  • 125
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

14 Answers14

74

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)) {
  ..
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • note for those who will google this : if you have a panel under your controls, you need to specify it such as : this.myPanel.Controls.OfType(), you can also use this.myPanel.Controls.OfType().Where(x => x.Name.StartsWith("specificName")) if you need to select comboboxes that have a specific name. – Rose Nov 25 '17 at 05:12
  • I assume `this` is a Form and code is running in same form. What if I want to read all the forms in assembly `Assembly.GetExecutingAssembly().GetTypes()` and then access `control`s in it on runtime to modify some property? – AaA Jan 16 '18 at 04:17
62

You're looking for

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
  }
}
JustLoren
  • 3,224
  • 3
  • 27
  • 34
8

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
}
Mathlec
  • 318
  • 1
  • 6
5

Also you can use LINQ. For example for clear Textbox text do something like:

this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);
Ali
  • 3,373
  • 5
  • 42
  • 54
4
foreach (Control X in this.Controls)
{
  if (X is TextBox)
  {
    (X as TextBox).Text = string.Empty;
  }
}
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
3

You can do the following:

foreach (Control X in this.Controls)
{
    TextBox tb = X as TextBox;
    if (tb != null)
    {
        string text = tb.Text;
        // Do something to text...
        tb.Text = string.Empty; // Clears it out...
    }
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

A lot of the above work. Just to add. If your textboxes are not directly on the form but are on other container objects like a GroupBox, you will have to get the GroupBox object and then iterate through the GroupBox to access the textboxes contained therein.

foreach(Control t in this.Controls.OfType<GroupBox>())
{
   foreach (Control tt in t.Controls.OfType<TextBox>())
   {
        // do stuff
   }
}
0
foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
//instead of above line we can use 
     ***  x.resetText();
  }
}
sandy
  • 1
0

Check this:

foreach (Control x in this.Controls)
{
    if (x is TextBox)
    {
        x.Text = "";
    }
}
Prasad Jadhav
  • 5,090
  • 16
  • 62
  • 80
0

simple using linq, change as you see fit for whatever control your dealing with.

        private void DisableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = false;
        }
    }

    private void EnableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = true;
        }
    }
DirtyHowi
  • 111
  • 1
  • 5
0

Just add other control types:

public static void ClearControls(Control c)
{

    foreach (Control Ctrl in c.Controls)
    {
        //Console.WriteLine(Ctrl.GetType().ToString());
        //MessageBox.Show ( (Ctrl.GetType().ToString())) ;
        switch (Ctrl.GetType().ToString())

        {
            case "System.Windows.Forms.CheckBox":
                ((CheckBox)Ctrl).Checked = false;
                break;

            case "System.Windows.Forms.TextBox":
                ((TextBox)Ctrl).Text = "";
                break;

            case "System.Windows.Forms.RichTextBox":
                ((RichTextBox)Ctrl).Text = "";
                break;

            case "System.Windows.Forms.ComboBox":
                ((ComboBox)Ctrl).SelectedIndex = -1;
                ((ComboBox)Ctrl).SelectedIndex = -1;
                break;

            case "System.Windows.Forms.MaskedTextBox":

                ((MaskedTextBox)Ctrl).Text = "";
                break;

            case "Infragistics.Win.UltraWinMaskedEdit.UltraMaskedEdit":
                ((UltraMaskedEdit)Ctrl).Text = "";
                break;

            case "Infragistics.Win.UltraWinEditors.UltraDateTimeEditor":
                DateTime dt = DateTime.Now;
                string shortDate = dt.ToShortDateString();
                ((UltraDateTimeEditor)Ctrl).Text = shortDate;
                break;

            case "System.Windows.Forms.RichTextBox":
                ((RichTextBox)Ctrl).Text = "";
                break;


            case " Infragistics.Win.UltraWinGrid.UltraCombo":
                ((UltraCombo)Ctrl).Text = "";
                break;

            case "Infragistics.Win.UltraWinEditors.UltraCurrencyEditor":
                ((UltraCurrencyEditor)Ctrl).Value = 0.0m;
                break;

            default:
                if (Ctrl.Controls.Count > 0)
                    ClearControls(Ctrl);
                break;

        }

    }
}
sth
  • 222,467
  • 53
  • 283
  • 367
0

Even better, you can encapsule this to clear any type of controls you want in one method, like this:

public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
        {
            foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
            foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;

            if (!limpiar) return;
            {
                foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
                foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = @"-1";
            }
        }
0
private IEnumerable<TextBox> GetTextBoxes(Control control)
{
    if (control is TextBox textBox)
    {
        yield return textBox;
    }

    if (control.HasChildren)
    {
        foreach (Control ctr in control.Controls)
        {
            foreach (var textbox in GetTextBoxes(ctr))
            {
                yield return textbox;
            }
        }
    }
}
Henry
  • 41
  • 2
0

I found this to work very well, but initially I have my textboxes on a panel so none of my textboxes cleared as expected so I added

this.panel1.Controls.....  

Which got me to thinking that is you have lots of textboxes for different functions and only some need to be cleared out, perhaps using the multiple panel hierarchies you can target just a few and not all.

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

howie
  • 2,587
  • 3
  • 27
  • 43