Say I have TextBox1, TextBox2, TextBox3...etc is there a better way to clear all of them then this...

Hey guys,

say I have 4 text boxes, in this case i'll just say they are TextBox1, TextBox2, TextBox3 and TextBox4. Now lets say I want to write a small routine that will clear all of them

would i have to do

TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";

Or is there a way to do it in a for loop that way I don't have the redundant code?


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can go over all Form (for Win app), respectively Page (for ASP.NET) controls and if the given control is a text box - clear it. However this will clear all text boxes on the form/page. Otherwise you could add all the text boxes to a collection and go over it like this:

ArrayList tbs = new ArrayList();
tbs.Add (TextBox1);
tbs.Add (TextBox2);
tbs.Add (TextBox3);
tbs.Add (TextBox4);

foreach (TextBox tb in tbs)
  tb.Text = "";

This is worth only if you often have to handle the same collection of text boxes. If it's only ones, you better make it your way

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
A Bit easier then you're doing:

TextBox1.Text = TextBox2.Text = TextBox3.Text = TextBox4.Text = "";

                  foreach(Control ctrl in this.Controls)
                        if(ctrl.GetType().ToString().IndexOf("TextBox") > 0)
                              ctrl.Text = String.Empty;

S Sansanwal

Control c = new Control;
Foreach (c in this.Controls)
             if (c.GetType = TextBox)
                     ctrl.Text = "";

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.