How to loop through all textbox on the form and clear its values

  • Thread starter Thread starter Thonglao Rud
  • Start date Start date
T

Thonglao Rud

I'm trying to clear all textbox on the form.

foreach (Control c in this.Controls)
{
//if (c.GetType() == typeof(TextBox))
if (c is TextBox)
{
// Found it
c.Text = "";
MessageBox.Show(c.Name.ToString());
}
}

However, this code can not effect with TextBox that inside groupbox in my form.
What is wrong?
 
I'm trying to clear all textbox on the form.

foreach (Control c in this.Controls)
{
//if (c.GetType() == typeof(TextBox))
if (c is TextBox)
{
// Found it
c.Text = "";
MessageBox.Show(c.Name.ToString());
}
}

However, this code can not effect with TextBox that inside groupbox in my form.
What is wrong?

Well, the TextBox in a GroupBox isn't directly inside your form - so
you should call the same method recursively for any container control.
It's probably easiest to actually call it recursively for *all*
controls, seeing as the Controls property is inherited from Control
itself, but that may well not be the most efficient way.
 
I think you can use GetStyle on the control to determine if it's a container
(check for the style ContainerControl). This might be a bit more efficient
than iterating through the Controls collection of every control.
 
If it's not a container control, the Controls count would be 0 and so, there
won't be any efficiency lost/gained.

-vJ

John Wood said:
I think you can use GetStyle on the control to determine if it's a
container
(check for the style ContainerControl). This might be a bit more efficient
than iterating through the Controls collection of every control.
 
Other than creating/disposing the enumerator instance unnecessarily for each
control... which is why I suggested using GetStyle to see if it's a
container. :)

Vijaye Raji said:
If it's not a container control, the Controls count would be 0 and so, there
won't be any efficiency lost/gained.

-vJ
 
Thank you all! I really appreciate it.
Here my modified code:

foreach (Control c in this.Controls)
{
if (c is TextBox)
{
c.Text = "";
}
if ((c.GetType().Name == "GroupBox"))
{
foreach (Control cc in c.Controls)
if (cc is TextBox)
{
cc.Text = "";
}
}
}

Ugly code but works for me :)
Thanks again.
 
Ah.. true! Good point

John Wood said:
Other than creating/disposing the enumerator instance unnecessarily for
each
control... which is why I suggested using GetStyle to see if it's a
container. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top