Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
清除文本框和组合框c#_C#_Winforms - Fatal编程技术网

清除文本框和组合框c#

清除文本框和组合框c#,c#,winforms,C#,Winforms,我想清除所有的文本框、组合框,并在按下按钮时将numericupdown重置为零 最好的方法是什么。抱歉,如果有人觉得这个q很愚蠢。如果这是WinForms,请遍历所有控件并重置它们 foreach (Control c in this.Controls) { if (c is TextBox) { ((TextBox)c).Text = ""; } else if (c is ComboBox) { ((ComboBox)c).Se

我想清除所有的文本框、组合框,并在按下按钮时将numericupdown重置为零


最好的方法是什么。抱歉,如果有人觉得这个q很愚蠢。

如果这是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;
   }
}

如果您使用的是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);
}


这是用于WinForms还是WPF?这是Windows窗体应用程序1)这只清除顶级文本框2)它只清除文本框1)这仍然只清除文本框2)你现在没有清除顶级控件。这是递归的,我刚刚测试过。。如果我做得不对,请指出。。我在看父控件,它仍然应该循环通过父控件的子控件。这不会工作,因为你不是铸造c<代码>如果(c是文本框)((文本框)c).Clear()你不必强制转换,我正在测试,如果它是文本框,那么它会清除。。富士公司确实这样做了,所以我不知道你在说什么。。在决定强制转换类型之前,最好先检查类型。我可能是错的,但我认为不需要条件
HasChildren
。在没有条件的情况下,它仍然可以工作,但是使用
if
语句,它只会在需要时通过children控件。感谢您的回答。除了一件事,它是有效的。numericupdown也被清除(空),而不是设置为值0。设置为-1应有助于保持与清除相反的值。对于-1,范围值会出现异常。您可能需要检查控件是否为类型
组合框
,而不是强制转换。。。
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); 
        } 
    } 
}