How To Programmatically And Recursively Clear All Form Controls



TODO:

Have you ever wanted to recursively clear a screen, without the need to manually clear each control?  This can be extremely helpful when it comes to large forms.

 

SOLUTION:

public void ClearControls(Control InControl, bool ClearLists, bool SetRadioButtonDefaultToFirstItem, bool SetDropDownDefaultToFirstItem)
{
    foreach (Control control in InControl.Controls)
    {
        //if its a check box, just clear the text
        if (control is CftcTextBox)
        {
            ((CftcTextBox)control).Text = string.Empty;
        }
        else if (control is CheckBoxList)
        {
            //deselect each check box item.
            foreach (System.Web.UI.WebControls.ListItem item in ((CheckBoxList)control).Items)
            {
                item.Selected = false;
            }
        }
        else if (control is DropDownList)
        {
            //deselect all items
            foreach (System.Web.UI.WebControls.ListItem item in ((DropDownList)control).Items)
            {
                item.Selected = false;
            }

            //if we choose, we now select the first item in list
            if (SetDropDownDefaultToFirstItem)
            {
                if(((DropDownList)control).Items.Count > 0)
                {
                    ((DropDownList)control).SelectedIndex = 0;
                }
            }
        }
        else if (control is System.Web.UI.WebControls.ListBox)
        {
            //if we clear lists, then remove all items.  otherwise, just deselect all list items.
            if (ClearLists)
            {
                ((System.Web.UI.WebControls.ListBox)control).Items.Clear();
            }
            else
            {
                foreach (System.Web.UI.WebControls.ListItem item in ((System.Web.UI.WebControls.ListBox)control).Items)
                {
                    item.Selected = false;
                }
            }
        }
        else if (control is RadioButtonList)
        {
            //default to the first item, if we choose to
            if (SetRadioButtonDefaultToFirstItem)
            {
                if (((RadioButtonList)control).Items.Count > 0)
                {
                    ((RadioButtonList)control).Items[0].Selected = true;
                }
            }
        }

        //now call recursively
        if (control.HasControls())
            ClearControls(control, ClearLists, SetRadioButtonDefaultToFirstItem, SetDropDownDefaultToFirstItem);
    }
}

 

NOTES:

There are no notes on this topic.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading