我正在使用以下代码清除表单中的所有文本框。
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/