Article

Clear All fields like TextBox, DropDownList, CheckBox, RadioButton, Label after Form submission in ASP.Net, C#

01 Jun 2015 Kamal Pratap
2 Comments 3748 Views
C#



Here we explain how to clear all controls in asp.net using C#. In this code we use only one method for clear all type controls in Asp.Net. Call this method from code behind after form submission.

C# Code :

    protected void Button1_Click(object sender, EventArgs e)
    {
        ClearControls(this);
    }
    public void ClearControls(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if ((c.GetType() == typeof(TextBox)))  //Clear TextBox
            {
                ((TextBox)(c)).Text = "";
            }
            if ((c.GetType() == typeof(DropDownList)))  //Clear DropDownList
            {
                ((DropDownList)(c)).ClearSelection();
            }
            if ((c.GetType() == typeof(CheckBox)))  //Clear CheckBox
            {
                ((CheckBox)(c)).Checked = false;
            }
            if ((c.GetType() == typeof(CheckBoxList)))  //Clear CheckBoxList
            {
                ((CheckBoxList)(c)).ClearSelection();
            }
            if ((c.GetType() == typeof(RadioButton)))  //Clear RadioButton
            {
                ((RadioButton)(c)).Checked = false;
            }
            if ((c.GetType() == typeof(RadioButtonList)))  //Clear RadioButtonList
            {
                ((RadioButtonList)(c)).ClearSelection();
            }
            if ((c.GetType() == typeof(HiddenField)))  //Clear HiddenField
            {
                ((HiddenField)(c)).Value = "";
            }
            if ((c.GetType() == typeof(Label)))  //Clear Label
            {
                ((Label)(c)).Text = "";
            }
            if (c.HasControls())
            {
                ClearControls(c);
            }
        }
    }

 

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

  1. very nice!! Saves lots of time.

Leave a Comment