Clear multiple text boxes with a button in C#
c#, textbox, winforms
Solution
void ClearAllText(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
((TextBox)c).Clear();
else
ClearAllText(c);
}
}
To use the above code, simply do this:
ClearAllText(this);
Problem
I use .NET framework 4. In my form, I have 41 text boxes. I have tried with this code: ``` private void ClearTextBoxes() { Action<Control.ControlCollection> func = null; func = (controls) => { foreach (Control control in controls) if (control is TextBox) (control as TextBox).Clear(); else func(control.Controls); }; func(Controls); } ``` And this code: ``` private void ClearTextBoxes(Control.ControlCollection cc) { foreach (Control ctrl in cc) { TextBox tb = ctrl as TextBox; if (tb != null) tb.Text = String.Empty; else ClearTextBoxes(ctrl.Controls); } } ``` This still does not work for me. When I tried to clear with this code `TextBoxName.Text = String.Empty;` the textbox success cleared but one textbox, still had 40 textbox again. How do I solve this? EDIT I put in this: ``` private void btnClear_Click(object sender, EventArgs e) { ClearAllText(this); } void ClearAllText(Control con) { foreach (Control c in con.Controls) { if (c is TextBox) ((TextBox)c).Clear(); else ClearAllText(c); } } ``` but still not work. Edit I used panels and splitter.