how can we clear the all form controls on winform?

c#-4.0, winforms

Solution

For `TextBox` and `ComboBox`

    public static void ClearSpace(Control control)
    {
        foreach (Control c in control.Controls)
        {
            var textBox = c as TextBox;
            var comboBox = c as ComboBox;

            if (textBox != null)
                (textBox).Clear();

            if (comboBox != null)
                comboBox.SelectedIndex = -1;

            if (c.HasChildren)
                ClearSpace(c);
        }
    }

Usage:

        ClearSpace(this); //Control

Problem

I want to clear all controls specially textbox nad combobox. and I am using the following control to clear all fields. ``` private void ResetFields() { foreach (Control ctrl in this.Controls) { if (ctrl is TextBox) { TextBox tb = (TextBox)ctrl; if (tb != null) { tb.Text = string.Empty; } } else if (ctrl is ComboBox) { ComboBox dd = (ComboBox)ctrl; if (dd != null) { dd.Text = string.Empty; dd.SelectedIndex = -1; } } } } ``` The above code is not working properly in group box. In group box I have combo box and text box as well. Combo box shows the selected index = 1 of the group box. I also want to clear these controls as well. Any suggestions ????

Original source

Related problems