About the author

Rob Schieber is a developer in Columbus, Ohio.
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Recursive FindControl

This is my recursive FindControl function.  It works just like the standard findControl, only it doesn't return null if it doesn't find the controlId in the first child, it searches all controls in the heirarchy.  There are performance implications of using a recursive find... which may be why the standard findcontrol functions don't do this.  So I wouldn't use it everywhere.  In any event this works for me.  

Click below to download.

RecursiveFind.txt (1.15 kb)

   1:          /// <summary>
   2:          /// Finds a control within the control paramter
   3:          /// </summary>
   4:          /// <typeparam name="T">Expected control returned</typeparam>
   5:          /// <param name="control">parent control</param>
   6:          /// <param name="controlId">child control id</param>
   7:          /// <returns></returns>
   8:          private T recursiveFind<T>(Control control, string controlId) where T : Control
   9:          {
  10:              T foundControl = null;
  11:   
  12:              if (control.ID == controlId)
  13:                  return (T)control;
  14:   
  15:              foreach (Control childControl in control.Controls)
  16:              {
  17:                  if (childControl.ID == controlId)
  18:                  {
  19:                      return (T)childControl;
  20:                  }
  21:                  else //check child controls
  22:                  {
  23:                      if (Controls.Count > 0)
  24:                      {
  25:                          foundControl = recursiveFind<T>(childControl, controlId);
  26:   
  27:                          if (foundControl != null)
  28:                              return foundControl;
  29:                      }
  30:                  }
  31:              }
  32:   
  33:              return foundControl;
  34:          }

 


Tags: ,
Categories: General
Posted by sheebz on Thursday, June 19, 2008 11:00 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Monday, October 06, 2008 6:33 PM