title: Loop through all controls on asp.net webpage
body: <p>I need to loop through all the controls in my asp.net webpage and do something to the control.  In one instance I'm making a giant string out of the page and emailing it to myself, and in another case I'm saving everything to a cookie.</p>
  
  <p>The problem is masterpages and items with collections of controls inside them.  I want to be able to pass in a Page to the method, then have that method be generic enough to loop through all controls in the inner-most content page and work with them.  I've tried doing this with recursion, but my recursion is incomplete.  </p>
  
  <p>I want to pass a Page object into a method, and have that method loop through all controls in the innermost content page.  How can I achieve this?</p>
  
  <pre><code>    private static String controlToString(Control control)
  {
      StringBuilder result = new StringBuilder();
  
      String controlID = String.Empty;
  
      Type type = null;
  
      foreach (Control c in control.Controls)
      {
          try
          {
              controlID = c.ID.ToString();
  
              if (c is IEditableTextControl)
              {
                  result.Append(controlID + ": " + ((IEditableTextControl)c).Text);
                  result.Append("&lt;br /&gt;");
              }
              else if (c is ICheckBoxControl)
              {
                  result.Append(controlID + ": " + ((ICheckBoxControl)c).Checked);
                  result.Append("&lt;br /&gt;");
              }
              else if (c is ListControl)
              {
                  result.Append(controlID + ": " + ((ListControl)c).SelectedValue);
                  result.Append("&lt;br /&gt;");
              }
              else if (c.HasControls())
              {
                  result.Append(controlToString(c));
              }
  
              //result.Append("&lt;br /&gt;");
          }
          catch (Exception e)
          {
  
          }
      }
  
      return result.ToString();
  }
  </code></pre>
  
  <p>Without Try/catch</p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object.</p>
  </blockquote>
  
  <p>On line controlID = .....</p>