我们如何清除winform上的所有表单控件?

Muh*_*zad 3 winforms c#-4.0

我想清除所有控件特别是textbox nad组合框.我正在使用以下控件来清除所有字段.

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;
                }
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

上面的代码在组框中无法正常工作.在组框中我也有组合框和文本框.组合框显示组框的选定索引= 1.我也想清除这些控件.有什么建议 ????

spa*_*jce 10

为TextBox和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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

用法:

        ClearSpace(this); //Control
Run Code Online (Sandbox Code Playgroud)