Sunday, 13 February 2011

Asp.Net: Generic Recursive FindControl Method

Question:
How to find a control in the whole page not just in the child collection?
How to find recursively a control in the child hierarchy of a control?


Answer:
You create a little recursive method passing in the parent and a condition (Predicate delegate on controls) that tests what you want to find.

Here is an example
public static T FindFirst<T>(Control ctrl, Predicate<Control> predicate) where T : Control 
{ 
    if (predicate(ctrl)) 
    { 
        return ctrl as T; 
    } 
    foreach (Control innerCtrl in ctrl.Controls) 
    { 
        T found = FindFirst<T>(innerCtrl , predicate);
        if (found != null) 
        {
            return found; 
        } 
    } 
    return null; 
} 

1 comment:

Anonymous said...

If the result's type is not T then the method returns null even though the execution of the predicate returns something that isn't null. Shouldn't you try to cast ctrl before running the predicate? Then, the predicate could be typed as Predicate<T>.