【问题标题】:Default control collection默认控件集合
【发布时间】:2012-12-01 17:06:35
【问题描述】:

当我使用设计器创建控件并将其添加到我的WinForm 时,我的控件是否会与其他所有控件一起自动添加到集合中?

假设有 20 个 TextBox,我需要同时清除它们,而不是这样称呼它:

txtbox1.Clear();
txtbox2.Clear();
txtbox3.Clear();
...

我知道我应该在没有设计器的情况下手动创建每个控件并将它们添加到集合中,但现在为时已晚。那么知道我是否可以访问整个控件组吗?

【问题讨论】:

    标签: c# winforms collections controls


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 正是我刚刚发现的。虽然你的版本有点太复杂了。但正是感谢我需要的逻辑
    【解决方案2】:

    哦,在我写完我的问题后,我实际上发现了如何做到这一点。 我可以在this.controls 上使用foreach loop。 然后我测试控件是否为TextBox

    foreach (Control x in this.Controls)
    {
      if (x is TextBox)
      {
        ((TextBox)x).Text = String.Empty;
      }   
    }
    

    【讨论】:

    • 请注意,这将在容器上失败:您需要像 Garry 那样深入挖掘
    猜你喜欢
    • 2019-01-24
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2012-04-08
    • 1970-01-01
    • 2017-09-22
    • 2018-12-03
    相关资源
    最近更新 更多