清除文本框和组合框c#

时间:2013-02-14 17:12:25

标签: c# winforms

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

这是最好的方法。对不起,如果有人发现这个q傻。

3 个答案:

答案 0 :(得分:2)

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

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

答案 2 :(得分:-1)

如果这是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;
   }
}
相关问题