【问题标题】:Clear All textBoxes (Any Shortcut)清除所有文本框(任何快捷方式)
【发布时间】:2013-12-09 15:43:22
【问题描述】:

我有几个文本框用于输入,然后有几个文本框用于结果。 有什么快捷方式可以清除表单上的所有条目吗?

例如aTextBox.Clear();

【问题讨论】:

标签: c# winforms


【解决方案1】:

如果所有文本框都是表单的直接子级,则可以使用 LINQ:

yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());

【讨论】:

    【解决方案2】:

    您将需要循环所有表单控件并检查类型是否为文本框,然后 .Text = string.empty

    【讨论】:

    • 考虑将此作为扩展方法实现。
    • 另外,正如已删除的评论所述,您还需要检查表单上的所有容器控件。
    • 是的,这会导致嵌套循环,所以@Frédéric 的答案更好stackoverflow.com/questions/7034161/…
    • 不,这将导致递归函数。如果你在这里使用嵌套循环,你就走错了路。
    • 而且 Freddy 的代码甚至没有处理容器控件中的文本框。
    【解决方案3】:
    var cntrlCollections = GetAll(this,typeof(TextBox));
    
           foreach (Control ctrl in cntrlCollections)
            {
    
                if (ctrl is TextBox)
                {
                    ctrl.Text = " ";
                }
            }      
    
    public IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();
    
            return controls.SelectMany(ctrl=>GetAll(ctrl,type)).Concat(controls).Where
                   (c=>c.GetType() ==type);
        }
    

    在单击事件中像上面一样调用此函数以清除所有文本框。希望这对您有所帮助。

    【讨论】:

      【解决方案4】:

      评论 Frederic - 您需要使用 ActiveForm yourform.ActiveForm.Controls. ...

      因为yourform.Controls. ... 丢了一个错误:

      An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.Controls.get

      申请VS2012Express

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-27
        • 2011-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多