Clearing all textboxes

  • Thread starter Thread starter Savvas
  • Start date Start date
S

Savvas

Hi everybody,

I have a lot of textboxes on my form and a "Clear" button. Is there a
way with a for loop or something to clear the textboxes, instead of
writing textboxName.clear?

Thanks a lot
 
Savvas said:
I have a lot of textboxes on my form and a "Clear" button. Is there a
way with a for loop or something to clear the textboxes, instead of
writing textboxName.clear?

You could loop through the form's Controls property, find the text boxes
and clear them, like this:

foreach (Control control in Controls) {
TextBox textBox = control as TextBox;
if (textBox != null)
textBox.Clear();
}

The problem is that maybe your form contains a hierarchy of controls, as
opposed to a flat structure, if for example you have panels or group
boxes on the form. In that case, you'd have to iterate into the
hierarchy to be able to find all the text boxes you want. From the top
of my head, maybe like this:

void ClearTextBoxes(Control control) {
foreach (Control childControl in control.Controls) {
TextBox textBox = childControl as TextBox;
if (textBox != null)
textBox.Clear();
if (childControl.Controls.Count > 0)
ClearTextBoxes(childControl);
}
}

You can call this method and pass in the form (or 'this', if you're
already in the form) and it should iterate recursively into the
hierarchy, find all text boxes and clear them.

Mind you, this will not be as performant as clearing the text boxes by
distinct statements, but I think on a reasonably sized form it shouldn't
do any harm.

Hope this helps!



Oliver Sturm
 
Thanks a lot Oliver

I will try that code out, however, i found this which works fine

For Each MeuControl In Me.GroupBox1.Controls
If TypeOf MeuControl Is TextBox Then
MeuControl.Text = ""
End If
Next MeuControl
 
Back
Top