c# - 清除 Windows 窗体中的所有文本框,特殊文本框除外

标签 c# winforms

我正在使用以下代码清除表单中的所有文本框。

protected static IEnumerable<Control> GetAllChildren(Control root)
        {
            var stack = new Stack<Control>();
            stack.Push(root);
            while (stack.Any())
            {
                var next = stack.Pop();
                foreach (Control child in next.Controls)
                    stack.Push(child);
                yield return next;
            }
        }

internal static void ResetTextBoxes(Control root, string resetWith = "", params TextBox[] except)
        {
            try
            {
                foreach (TextBox txt in GetAllChildren(root).OfType<TextBox>())
                {
                    foreach (TextBox txtException in except)
                    {
                        if (txtException.Name != txt.Name)
                        {
                            txt.Text = resetWith == "" ? string.Empty : resetWith;
                        }
                    }
                }
            }
            catch (Exception ex) { throw ex; }
        }

我尝试使用参数将一些我不想清除的特殊文本框分开,但它仍然会清除所有框。需要帮助,请。

最佳答案

GetAllChildren 的简化版本:

protected static IEnumerable<Control> GetAllChildren(Control root) {
  return new Control[] { root }
    .Concat(root.Controls
      .OfType<Control>()
      .SelectMany(item => GetAllChildren(item)));
}

和更短的 Linq:

var source = GetAllChildren(root)
  .OfType<TextBox>()
  .Where(ctrl => !except.Contains(ctrl));

foreach (var textBox in source)
  textBox.Text = resetWith;

您当前实现的问题在内循环中:

foreach (TextBox txtException in except)
  if (txtException.Name != txt.Name)
    txt.Text = resetWith == "" ? string.Empty : resetWith;

如果您至少有 两个 具有不同名称的异常

 txtException.Name != txt.Name

不可避免地满足(任何txt.Name不等于第一个异常或第二个异常)

关于c# - 清除 Windows 窗体中的所有文本框,特殊文本框除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617168/

相关文章:

c# - Windows Mobile 存储卡问题

c# - 构建与视频驱动程序 VS2012 相关的 WPF 问题

c# - c#.net 中用于 winforms 的气球类

c# - 使用 control.BackgroundImage = Image.FromStream(memStream) 时出现内存不足异常;

c# - FileMode.Create 和 FileMode.Truncate 有什么区别?

c# - 使构建前和构建后的事件脚本漂亮吗?

c# - 如何在我的类(class)之间设置委托(delegate)?

.net - 使用.NET WinForm打印预览ZPL II命令,然后将其发送到Zebra打印机

.net - .NET 中的双向数据绑定(bind)不起作用,即使使用 INotifyPropertyChanged 对象也是如此

c# - select new 中的 Linq where 子句