Clearing all TextBoxes text from a Form using C#

When we develop any application form, then there will be a new button where we need to perform clear operation.
We can clear all the TextBox texts from a Form or a Control like panel, tabe pages using following code

foreach (Control c in this.Controls) 
            {
                if (c is TextBox) 
                {
                    c.Text = string.Empty;
                }
            }

Or we can do following

 foreach (Control c in this.Controls)
            {
                TextBox tb = (c as TextBox);
                if (tb != null) 
                {
                    tb.Text = string.Empty;
                }
            }
  • sundar

    this is not clear. and please give a perfect example

    • Thanks for comments.
      Here “this” means your application form.

      If you are in Form1 then “this” means instance of Form1 and “this.Controls” means Controls under Form1.

      If you want to clear all text box under a GroupBox(“Name=gbGroupBox”) then you can use gbGroupBox.Controls instead of this.Controls.

      Hope you are clear.

  • Nullity

    The second one works great for, me, thanks!