Àndres
Àndres

Reputation: 121

Any way to clear all fields in a form at once?

i just started learning C# and i was wondering if it's possible to clear the content of all the textboxes for example in my form.

I know how to clear one by one but it's not practical for me.

thanks!

edit: I found my answer thank you all very much

Upvotes: 3

Views: 11179

Answers (7)

Timothy Odhiambo
Timothy Odhiambo

Reputation: 45

my code is old school with panels and controls placed in the panels. This is how I went about it WebUtil.ResetControls(PanelMD.Controls);

Upvotes: 0

litpost
litpost

Reputation: 105

If you need to clear just what you want you can use "Tag" for that. Just mark your controls with tag "clear":

            foreach (Control c in Controls)
        {
            if (c.Tag == "clear")

            {
                c.Text = string.Empty;
            }
        }

Upvotes: 0

spyrax10
spyrax10

Reputation: 5

Try this:

Form.Controls.OfType<Textbox>().ToList().ForEach(t => t.Text = "");

Upvotes: -1

Hassan Kazmouhi
Hassan Kazmouhi

Reputation: 11

private void ClearTextBoxes(ControlCollection controls)
{
    foreach(control c in Controls)
        if(c is TextBox)
            c.Clear();
}

Upvotes: 1

Ahmed Aboumalek
Ahmed Aboumalek

Reputation: 623

You can use the following loop to clear all the textbox objects in your active form:

foreach (Control c in this.Controls) 
{
    if (c.GetType() == typeof(TextBox))
    {
        c.Clear();
    }
}

You can also use the loop inside a function and give it a Boolean return value to test if it was successfuly executed.

Upvotes: 4

MrSykkox
MrSykkox

Reputation: 528

I bet you are looking for a solution similar to this one : Foreach Control in form, how can I do something to all the TextBoxes in my Form?

What you want to do is loop through all the controls in the Form, if the control is a TextBox you want to clear it

Upvotes: 1

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43916

If you only want to clear TextBoxes you can do it easily like this:

foreach(TextBox tb in this.Controls.OfType<TextBox>())
    tb.Text = string.Empty;

But that will only clear all the TextBoxes that are directly on the Form and not inside a GroupBox or Panel or any other container.

If you have TextBoxes inside other containers you need to recurse:

private void ClearTextBoxes(ControlCollection controls)
{
    foreach(TextBox tb in controls.OfType<TextBox>())
        tb.Text = string.Empty;
    foreach(Control c in controls)
        ClearTextBoxes(c.Controls);
}

Call this like ClearTextBoxes(this.Controls);

Upvotes: 4

Related Questions