Monday, March 19, 2007

A better FindControl: FindControlOf<T>

Whilst helping a colleague with some ASP.NET questions, I found a number of blocks enumerating the Controls collection for specific control types. Having to enumerate and determine the control type can become quite tedious, so I provided an iterator to simplify:

   1:  static IEnumerable FindControlsOf<T>(Control parent)
   2:      where T : class
   3:  {
   4:      foreach (Control control in parent.Controls)
   5:      {
   6:          T item = control as T;
   7:          if (item != null)
   8:          {
   9:              yield return item;
  10:          }
  11:   
  12:          // Don't enumerate the children, if control is type T as an optimization, since our
  13:          // typical search criteria is not container controls.  If the criteria changes, 
  14:          // remove the "item == null" check.
  15:          if (item == null && control.Controls.Count > 0)
  16:          {
  17:              foreach (T child in FindControlsOf<T>(control))
  18:              {
  19:                  yield return child;
  20:              }
  21:          }
  22:      }
  23:  }


Making it easy to enumerate controls of a specific type:

   1:  foreach (MyControl sa in FindControlsOf<MyControl>(pnlMyContainer))
   2:  {
   3:      ...
   4:  }


I should point out that this code generates recursive state machines depending on the depth of the hierarchy of controls, so it should be used carefully.

No comments: