Monday 3 August 2015

Clear all asp.net controls in code behind c#

Below is the method to clear controls

protected void btnSubmit_Click(object sender, EventArgs e)
{
          ClearFields(Page.Controls);

}


private void ClearFields(ControlCollection ctrls)
        {
            foreach (Control ctrl in ctrls)
            {
                if (ctrl is TextBox)
                {
                    ((TextBox)ctrl).Text = string.Empty;
                }
                else if (ctrl is DropDownList)
                {
                    ((DropDownList)ctrl).SelectedIndex = 0;
                }
                else if (ctrl is RadioButtonList)
                {
                    ((RadioButtonList)ctrl).ClearSelection();
                }
                else if (ctrl is CheckBoxList)
                {
                    ((CheckBoxList)ctrl).ClearSelection();
                }
                ClearFields(ctrl.Controls);
            }
        }

No comments:

Post a Comment