Back

Flexi Time System

Clearing Form Fields the Easy Way in ASP.net Using C#

Ever wanted to clear your fields in the form without having to set the text properties or selected items? Well below I have simple method to do this. The only real catch to this method is your fields have to be in a container. I usually put all my fields in panel, for example:

put your form fields here

The method below iterates through the form fields and clears them:

public void ClearFormFields(System.Web.UI.Control parent)
        {
            //where parent is a panel;
            foreach (Control c in parent.Controls)
            {
                if ((c.GetType() == typeof(TextBox)))
                {
                    // is it a textbox?            
                    TextBox t = (TextBox)c;
                    t.Text = "";
                }
                else if ((c.GetType() == typeof(DropDownList)))
                {
                    // is it a dropdown list?             
                    DropDownList d = (DropDownList)c;
                    d.ClearSelection();
                }
                else if ((c.GetType() == typeof(ListBox)))
                {
                    // is it a listbox?               
                    ListBox l = (ListBox)c;
                    l.ClearSelection();
                }
                else if ((c.GetType() == typeof(RadioButtonList)))
                {
                    // is it a radiobutton list?    
                    RadioButtonList rl = (RadioButtonList)c;
                    rl.ClearSelection();
                }
                else if ((c.GetType() == typeof(CheckBox)))
                {
                    // is it a checkbox?            
                    CheckBox chk = (CheckBox)c;
                    chk.Checked = false;
                }
                else if ((c.GetType() == typeof(CheckBoxList)))
                {
                    // is it a radiobutton list?    
                    CheckBoxList cl = (CheckBoxList)c;
                    cl.ClearSelection();
                }
                /*if (c.HasControls())
                {              
                    ClearFields(c);*/
               }
            }
        }

You can call this as follows:

ClearFormFields(this.panel);

 

 

Back


Make a Comment on this Article

Your Name:
Comment:

 

Net-Aspect Wakefield (West Yorkshire) Web Design Services Call 01924 918 177