How can we clear all winform controls?

I want to clear all controls specifically textbox nad combobox. and I am using the following control to clear all the 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 does not work as expected in a group. In a group box, I have a combo box and a text box. The Combo field shows the selected index = 1 in the group field. I also want to clear these controls. Any suggestions????

+3


source to share


1 answer


For TextBox

andComboBox

    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);
        }
    }

      



Application:

        ClearSpace(this); //Control

      

+9


source







All Articles