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

后端 未结 9 1531
长发绾君心
长发绾君心 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 05:46

    Try this:

    var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
    foreach (TextBox item in t)
    {
        item.Text = "";
    }
    
    0 讨论(0)
  • 2020-11-27 05:48

    We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls, the problem reveals it's nature: you have to recurse through all child controls.

    The code could look like this:

    private void CleanForm()
    {
        traverseControlsAndSetTextEmpty(this);
    }
    private void traverseControlsAndSetTextEmpty(Control control)
    {
    
        foreach(var c in control.Controls)
        {
            if (c is TextBox) ((TextBox)c).Text = String.Empty;
            traverseControlsAndSetTextEmpty(c);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:52

    Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).

     foreach (TextBox textBox in Controls.OfType<TextBox>())
        textBox.Text = "";
    
    0 讨论(0)
  • 2020-11-27 05:53

    I like lambda :)

     private void ClearTextBoxes()
     {
         Action<Control.ControlCollection> func = null;
    
         func = (controls) =>
             {
                 foreach (Control control in controls)
                     if (control is TextBox)
                         (control as TextBox).Clear();
                     else
                         func(control.Controls);
             };
    
         func(Controls);
     }
    

    Good luck!

    0 讨论(0)
  • 2020-11-27 05:55

    I improved/fixed my extension method.

    public  static class ControlsExtensions
    {
        public static void ClearControls(this Control frm)
        {
            foreach (Control control in frm.Controls)
            {
                if (control is TextBox)
                {
                    control.ResetText();
                }
    
                if (control.Controls.Count > 0)
                {
                    control.ClearControls();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:55

    You can try this code

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
    
    
            if(keyData==Keys.C)
            {
                RefreshControl();
                return true;
            }
    
    
            return base.ProcessCmdKey(ref msg, keyData);
        }
    
    0 讨论(0)
提交回复
热议问题