清除windows窗体中除特殊文本框外的所有文本框
本文关键字:文本 窗体 windows 清除 | 更新日期: 2023-09-27 17:58:49
我使用以下代码清除表单中的所有文本框。
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; }
}
我试着用params将一些我不想清除的特殊文本框分开,但它仍然清除了所有的框。需要帮助。
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
要么不等于第一个异常要么第二个异常)
之所以会发生这种情况,是因为您正在针对第二个集合的所有元素测试第一个集合中的所有元素,因此即使except
数组中存在文本框,其名称也不会与其他文本框匹配。使用Linq的Any
扩展方法:
internal static void ResetTextBoxes(Control root, string resetWith = "", params TextBox[] except)
{
foreach (TextBox txt in GetAllChildren(root).OfType<TextBox>())
{
if(!except.Any(t => t.Name == txt.Name))
{
txt.Text = resetWith == "" ? string.Empty : resetWith;
}
}
}
}
这是我使用的函数:
public void ClearAllFields(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox && c != null)
{
if (c.Name != "specialtxtbox1name" && c.Name != "specialtxtbox2name" && c.Name != "nameoftextbox") // just put in the name of special textBoxes between double quotes
c.Text = "";
}
else
{
ClearAllFields(c);
}
}
}
只需在需要的地方调用函数
示例:
private void InsertDatathenClearForm_Click(object sender, EventArgs e)
{
//Code
//.
//.
File.Create(filepath);
MessageBox.Show("All Textboxes Data saved successfully");
//Clear fxn
ClearAllFields(this);
}
.
}