Reputation: 6933
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
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