Asif Chowdhury Asif Chowdhury - 27 days ago 9
C# Question

Clear all textbox in a windows form except special ones

I'm using following code to clear all text boxes in a form.

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


I tried to separate some special text boxes those I don't want to be cleared by using params, but still it clears all the boxes. Need help, please.

Answer

Shorter version of GetAllChildren:

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

And shorter Linq:

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

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

The problem with your current implmentation is in the inner loop:

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

if you have at least two exceptions with different names that condition

 txtException.Name != txt.Name

will be inevitably satisfied (any txt.Name either not equal 1st exception or 2nd one)