Clear all controls in a Form

by Edward 09 December 2009 16:40

You might find yourself in a situation where you would like to clear all html controls in a form using a server command. Obviously,  forms will either small or a large number of input controls like textbox, dropdownlist, checkbox and radiobutton, etc.

In  the following "button click" example I will show you how to clear each control by first finding only “form” input controls, and then clear them to their default state(in my example they have to empty).

 

   1:  protected void Button1_Click(object sender, EventArgs e)
   2:          {
   3:              //Find controls in the web form
   4:              Control formCtrl = Page.FindControl("Form1");
   5:   
   6:              //For each control in the html form
   7:              foreach (Control ctrl in formCtrl.Controls)
   8:              {
   9:   
  10:                  //Clears TextBox
  11:                  if (ctrl is TextBox)
  12:                  {
  13:                      (ctrl as TextBox).Text = String.Empty;
  14:                  }
  15:   
  16:                  //Clears DropDown Selection
  17:                  if (ctrl is DropDownList)
  18:                  {
  19:                      (ctrl as DropDownList).ClearSelection();
  20:                  }
  21:   
  22:                  //Clears ListBox Selection
  23:                  if (ctrl is ListBox)
  24:                  {
  25:                      (ctrl as ListBox).ClearSelection();
  26:                  }
  27:   
  28:                  //Clears CheckBox Selection
  29:                  if (ctrl is CheckBox)
  30:                  {
  31:                      (ctrl as CheckBox).Checked = false;
  32:                  }
  33:   
  34:                  //Clears RadioButton Selection
  35:                  if (ctrl is RadioButtonList)
  36:                  {
  37:                      (ctrl as RadioButtonList).ClearSelection();
  38:                  }
  39:   
  40:                  //Clears CheckBox Selection
  41:                  if (ctrl is CheckBoxList)
  42:                  {
  43:                      (ctrl as CheckBoxList).ClearSelection();
  44:                  }
  45:              }
  46:   
  47:          }

 

Tags: ,

ASP.NET | Social Media

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List