Foreach Control in form, how can I do something to all the TextBoxes in my Form?

后端 未结 14 1511
野的像风
野的像风 2020-11-28 08:13

How can I use a Foreach Statement to do something to my TextBoxes?

foreach (Control X in this.Controls)
{
    Check if the controls is a TextBox, if it is de         


        
相关标签:
14条回答
  • 2020-11-28 08:31
    foreach (Control x in this.Controls)
    {
      if (x is TextBox)
      {
        ((TextBox)x).Text = String.Empty;
    //instead of above line we can use 
         ***  x.resetText();
      }
    }
    
    0 讨论(0)
  • 2020-11-28 08:35

    Also you can use LINQ. For example for clear Textbox text do something like:

    this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);
    
    0 讨论(0)
  • 2020-11-28 08:37

    You're looking for

    foreach (Control x in this.Controls)
    {
      if (x is TextBox)
      {
        ((TextBox)x).Text = String.Empty;
      }
    }
    
    0 讨论(0)
  • 2020-11-28 08:37

    A lot of the above work. Just to add. If your textboxes are not directly on the form but are on other container objects like a GroupBox, you will have to get the GroupBox object and then iterate through the GroupBox to access the textboxes contained therein.

    foreach(Control t in this.Controls.OfType<GroupBox>())
    {
       foreach (Control tt in t.Controls.OfType<TextBox>())
       {
            // do stuff
       }
    }
    
    0 讨论(0)
  • 2020-11-28 08:37
    private IEnumerable<TextBox> GetTextBoxes(Control control)
    {
        if (control is TextBox textBox)
        {
            yield return textBox;
        }
    
        if (control.HasChildren)
        {
            foreach (Control ctr in control.Controls)
            {
                foreach (var textbox in GetTextBoxes(ctr))
                {
                    yield return textbox;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 08:39

    The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.

    I recommend using an extension of Control that will return something more..queriyable ;)

    public static IEnumerable<Control> All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (Control grandChild in control.Controls.All())
                    yield return grandChild;
    
                yield return control;
            }
        }
    

    Then you can do :

    foreach(var textbox in this.Controls.All().OfType<TextBox>)
    {
        // Apply logic to the textbox here
    }
    
    0 讨论(0)
提交回复
热议问题