Link to home
Start Free TrialLog in
Avatar of prowebinteractiveinc
prowebinteractiveinc

asked on

.NET Clear all Textbox's in windows form

Hi

I have a bunch of textboxes that sit in 2 different GroupBox's that are in a tab control
I would like to be able to reset all textboxes and combo boxes

Thanks
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Try this
foreach (Control control in this.Controls)
{
  if (control.GetType() == typeof(TextBox) ||
      control.GetType() == typeof(ComboBox))
  {
    control.Text = "";
  }
}

Open in new window

That will not catch the controls inside the GroupPanels and TabControl.  You would have to do something like this method...call this method using ClearTextBoxes(this.Controls) and you're all set.

private void ClearTextBoxes( Control.ControlCollection controls )
      {
         foreach( Control control in controls )
         {
            if( control.Controls.Count > 0 )
               ClearTextBoxes( control.Controls );

            if( control.GetType() == typeof( TextBox ) ||
                control.GetType() == typeof( ComboBox ) )
            {
               control.Text = "";
            }
         }
      }
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RobRotterdam
RobRotterdam

A TabControl and a groupbox are controls themselves, with the first solution the textboxes on them won't be cleared.

I'd suggest you create an Utilities class in your application and in that class a static function:

public static clearTextboxes (object ClearObject) 
{
   foreach (Control control in ClearObject)
   {
     string ControlType = control.GetType().ToString();
      if (ControlType == "System.Windows.Forms.TextBox" || ControlType == "System.Windows.Forms.GroupBox"       
       {
             control.Text = ""; 
        }
      if (ControlType == "System.Windows.Forms.Panel" ||
          ControlType == "System.Windows.Forms.TabControl" ||
          ControlType == "System.Windows.Forms.GroupBox")
      {
           clearTextBoxes(control); 
      }
   }
}

Open in new window


On the forms you want to clear you create a button and in the on-click event you define:
ApplicationUtil.clearTextBoxes(this); 

Open in new window

Avatar of prowebinteractiveinc

ASKER

worked like a charm, not even anything to edit