title: How to terminate a recursive function and return a value
body: <p>I'm trying to find a TextBox control inside a ASP.NET page using a recursive function. When this control is found, i would like to terminate the function and return it.</p>
  
  <p>My main problem is that i'm unable to stop the recursive function and return the control.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>//execute recursive function to find a control in page by its id
  TextBox textbox = GetTextBoxByID(controlCollection, id);
  
  //recursive function
  private TextBox GetTextBoxByID(ControlCollection controlCollection, string id)
  {
      foreach (Control control in controlCollection)
      {
          if (control is TextBox)
          {
              TextBox tb = (TextBox)control;
  
              if (tb.ID == id)
              {
                  //return selected texbox and terminate this recursion
                  return tb;
              }
          }
  
          if (control.HasControls())
          {
              GetTextBoxByID(control.Controls, id);
          }
      }
  
      //no control found return null
      return null;
  }
  </code></pre>