Why aren't my TextBoxes being counted?

89 Views Asked by At

I'm trying to change the Text in my TextBoxes in a form but I can't find out how to account for all of my TextBoxes without doing them individually...

I've tried the following code; however, my int i returns 0.

int i = 0;

foreach (Control c in this.Controls)
{
    if (c.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
    {
        i++;
        ((TextBox)c).Text = CleanInput(((TextBox)c).Text);
    }
}

I'm just confused on how to grab all of my TextBoxes and check them...

2

There are 2 best solutions below

0
Graffito On BEST ANSWER

If all TextBoxes are not children of "this", use a recursive method:

CleanTextBoxes(this)

private void CleanTextBoxes(Control TheControl)
{ 
  foreach (Control c in TheControl.Controls)
  {
    if (c is TextBox) ((TextBox)c).Text = CleanInput(((TextBox)c).Text);
    else CleanTextBoxes(c) ;
   }
}
0
Salah Akbari On

Try this:

int i = 0;

foreach (Control c in this.Controls)
{
   if (c is TextBox)
    {
       i++;
       ((TextBox)c).Text = CleanInput(((TextBox)c).Text);
    }
}