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?

Thanks!

LVL 6
PoeticAudioAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
TheAvengerConnect With a Mentor Commented:
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
0
 
tusharashahConnect With a Mentor Commented:
A Bit easier then you're doing:

TextBox1.Text = TextBox2.Text = TextBox3.Text = TextBox4.Text = "";
0
 
s_sansanwalCommented:
try

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


Cheers,
S Sansanwal
0
 
basheer_basataCommented:

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

Basheer
0
All Courses

From novice to tech pro — start learning today.