Reset all the TextBoxes in c#: Windows Form

November 06, 2013 , 1 Comments

When we are doing some editing operations, sometimes we have to empty all the textboxes after or in-between the operation. If user have entered all the values and save all the data, then programmer have to clear the textboxes to operate again.

Drag-n-drop some textboxes on the form and a button also. The text of all the textboxes is set to “Welcome”, we are going to be clear all these textboxes with some lines of c# code. The form is look like the below image:

How to reset all the textboxes in c# windows Forms

In the click event of this button, write the following code:
foreach (var item in this.Controls)
if (item.GetType().Equals(typeof(TextBox)))
TextBox tb = item as TextBox;
tb.Text = string.Empty;

In this c# code, the loop will exist till all the controls of this form. In the next line check the type of control, if the type is TextBox then set the text property to string.Empty. This code will set the text property to blank string for all the textboxes. And after it the form will look like the below image.

How to reset all the textboxes in c# windows Forms

Using the same code we can set any value for any control having the same type. If we want to set some string to the textboxes then replace string.Empty to that string to be replaced.

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

1 comment:

  1. foreach (var item in this.Controls.OfType())
    item.Text = string.Empty;

    Alternately, one could go for:

    this.Controls.OfType().ToList().ForEach(tb=>{tb.Text = String.Empty});