【问题标题】:how can we clear the all form controls on winform?我们如何清除winform上的所有表单控件?
【发布时间】:2013-01-31 07:14:59
【问题描述】:

我想清除所有控件,特别是文本框和组合框。 我正在使用以下控件清除所有字段。

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

上面的代码在分组框中不能正常工作。在组框中,我也有组合框和文本框。组合框显示所选索引 = 1 的组框。我也想清除这些控件。 有什么建议吗????

【问题讨论】:

  • 您需要为所有孩子递归地执行此操作。
  • 任何类型的例子???如何递归地做到这一点
  • 你试过清除组合框中的项目吗.....根据我对这个问题的理解,我建议你

标签: winforms c#-4.0


【解决方案1】:

对于TextBoxComboBox

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

用法:

        ClearSpace(this); //Control

【讨论】:

  • 谢谢。我只需要添加其他控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2010-09-22
  • 2018-02-22
  • 2011-02-21
  • 2012-01-09
  • 1970-01-01
相关资源
最近更新 更多