How to clear the text of all textBoxes in the form?

后端 未结 9 1532
长发绾君心
长发绾君心 2020-11-27 05:15
private void CleanForm()
{
    foreach (var c in this.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }
            


        
相关标签:
9条回答
  • 2020-11-27 06:00
    private void CleanForm(Control ctrl)
    {
        foreach (var c in ctrl.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Text = String.Empty;
            }
    
            if( c.Controls.Count > 0)
            {
               CleanForm(c);
            }
        }
    }
    

    When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

    0 讨论(0)
  • 2020-11-27 06:03

    Your textboxes are probably inside of panels or other containers, and not directly inside the form.

    You need to recursively traverse the Controls collection of every child control.

    0 讨论(0)
  • 2020-11-27 06:06

    And this for clearing all controls in form like textbox, checkbox, radioButton

    you can add different types you want..

    private void ClearTextBoxes(Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).Clear();
                }
    
                if (c.HasChildren)
                {
                    ClearTextBoxes(c);
                }
    
    
                if (c is CheckBox)
                {
    
                    ((CheckBox)c).Checked = false;
                }
    
                if (c is RadioButton)
                {
                    ((RadioButton)c).Checked = false;
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题