Mkl Rjv
Mkl Rjv

Reputation: 6933

Create a function to clear a windows form(C#)

I'm trying to clear a windows form using a C# function.

I know the method for clearing individual controls like

username.Clear();
password.Clear();

But, it is a large form an the clear function looks a bit awkward.

I found a code online which looks like this.

private void ClearFields(System.Windows.Forms.Control.ControlCollection collection)
{
    foreach (Control c in collection)
    {
        if (c.HasChildren)
            ClearFields(c.Controls);
        if (c is TextBox)
        {
            if (!string.IsNullOrEmpty(c.Text))
                c.Text = "";
        }
    }
}

But, for this code, the password field alone does not get cleared. I'm clearing "TextBox" controls alone. Do I have to specify any other control name for clearing a password field even though both are basically "TextBox" controls?

Upvotes: 1

Views: 3594

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You should get controls which are TextBox controls (or TextBoxBase if you want also to clear MaskedTextBox and RichTextBox also) and call their Clear() method:

private void ClearTextBoxes(ControlCollection controls)
{
    foreach (Control c in collection)
    {
        if (c.HasChildren)
        {
            ClearTextBoxes(c.Controls);
            continue;
        }

        TextBox tb = c as TextBox; // or TextBoxBase
        if (tb != null)
            tb.Clear();
    }
}

As @Adriano already pointed, 'password' controls are simple TextBoxes in WinForms

Upvotes: 2

Related Questions