清除文本框和组合框c#

清除文本框和组合框c#

问题描述:

我想要清除所有的文本框,组合框和重置numericupdown回到零按下按钮。清除文本框和组合框c#

最新最好的办法做到这一点。对不起,如果有人发现这个愚蠢的。

+2

这是对的WinForms或WPF? – eandersson 2013-02-14 17:13:12

+0

它是Windows窗体应用程序 – user1903439 2013-02-14 17:15:35

如果您正在使用的WinForms,你可以使用以下方法来清除所有想要的控制。

public void ClearTextBoxes(Control control) 
{ 
    foreach (Control c in control.Controls) 
    { 
     if (c is TextBox) 
     { 
      if (!(c.Parent is NumericUpDown)) 
      { 
       ((TextBox)c).Clear(); 
      } 
     } 
     else if (c is NumericUpDown) 
     { 
      ((NumericUpDown)c).Value = 0; 
     } 
     else if (c is ComboBox) 
     { 
      ((ComboBox)c).SelectedIndex = 0; 
     } 

     if (c.HasChildren) 
     { 
      ClearTextBoxes(c); 
     } 
    } 
} 

然后激活它只需在表单中添加一个按钮,在后台代码如下。

private void button1_Click(object sender, EventArgs e) 
{ 
    ClearTextBoxes(this); 
} 
+0

我可能是错的,但我不认为'HasChildren'的条件是必要的。 – AbZy 2013-02-14 17:20:29

+0

它仍然没有工作,但与'if'声明只会经历的孩子,如果需要控制。 – eandersson 2013-02-14 17:31:06

+0

感谢您的回答。它除了一件事情以外。 – user1903439 2013-02-14 17:35:29

如果是这样的WinForms通过所有的控制循环,然后重新设置

foreach (Control c in this.Controls) 
{ 
    if (c is TextBox) 
    { 
     ((TextBox)c).Text = ""; 
    } 
    else if (c is ComboBox) 
    { 
     ((ComboBox)c).SelectedIndex = 0; 
    } 
    else if (c is NumericUpDown) 
    { 
     ((NumericUpDown)c).Value= 0; 
    } 
} 
+0

这只会清晰顶层控制。 – Servy 2013-02-14 17:17:36

+0

你应该想要检查控制是否是'ComboBox'类型而不是铸造... – MethodMan 2013-02-14 17:27:02

+0

我正在检查它... – gzaxx 2013-02-14 17:32:50

public void ClearTextBoxes(Control parent) 
{ 
    foreach(Control c in parent.Controls) 
    { 
     ClearTextBoxes(c); 
     if(c is TextBox) c.Text = string.Empty; 
     if(c is ComboBox) c.SelectedIndex = 0; 
    } 
} 

public void ClearTextBoxes(Control ctrl) 
{ 
    if (ctrl != null) 
    { 
     foreach (Control c in ctrl.Controls) 
     { 
      if (c is TextBox) 
      { 
       ((TextBox)c).Text = string.empty; 
      } 

      if(c is ComboBox) 
      { 
       ((ComboBox)c).SelectedIndex = 0; 
      } 
      ClearTextBoxes(c); 
     } 
    } 
} 
+1

1)这只会清除*文本框2)它只会清除文本框 – Servy 2013-02-14 17:18:23

+0

我将编辑此文件并发布递归代码Servy – MethodMan 2013-02-14 17:19:55

+0

1)此*仍*仅清除文本框2)您现在不清除顶层控制。 – Servy 2013-02-14 17:21:56