« Recursive FindControl(Of T As Control) | Main | Palermo4 at Twitter »

Recursive FindControl<T>

Need to find a control anywhere on the page or in a template?  Here is the code to find it recursively.  This example assumes the code is located in a custom base page.

 

  1 public T FindControl<T>(string id) where T : Control
  2 {
  3     return FindControl<T>(Page, id);
  4 }
  5 
  6 public static T FindControl<T>(Control startingControl, string id) where T : Control
  7 {
  8     // this is null by default
  9     T found = default(T);
 10 
 11     int controlCount = startingControl.Controls.Count;
 12 
 13     if (controlCount > 0)
 14     {
 15         for (int i = 0; i < controlCount; i++)
 16         {
 17             Control activeControl = startingControl.Controls[i];
 18             if (activeControl is T)
 19             {
 20                 found = startingControl.Controls[i] as T;
 21                 if (string.Compare(id, found.ID, true) == 0) break;
 22                 else found = null;
 23             }
 24             else
 25             {
 26                 found = FindControl<T>(activeControl, id);
 27                 if (found != null) break;
 28             }
 29         }
 30     }
 31     return found;
 32 }       
Posted on Friday, April 13, 2007 at 12:21PM by Registered CommenterJ. Michael Palermo IV in , | CommentsPost a Comment

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.
Editor Permission Required
You must have editing permission for this entry in order to post comments.