Search code examples
c#.netformstextboxsystem.web.ui.webcontrols

Why aren't my TextBoxes being counted?


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...


Solution

  • 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) ;
       }
    }