Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear multiple text boxes with a button in C#

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

Image

I used panels and splitter.

like image 611
Puja Surya Avatar asked Dec 07 '22 04:12

Puja Surya


1 Answers

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);
like image 102
User2012384 Avatar answered Dec 10 '22 13:12

User2012384