Tuesday 1 May 2007

ASP.Net Generic Recursive FindControl

I was attempting to find a nested control on my page today and realised that the built in FindControl is useless for this. A bit of googling turned up a post by Eric Porter and a neat little function he'd written to solve the problem.

Mine has the same signature but actually works. :P
public static T FindControl(ControlCollection controls, string controlId) where T : class
{
T found = default(T);
int i = -1;
while ((controls != null) &&amp; (found == null) && (++i < found =" ((controls[i]" id ="="">(controls[i].Controls, controlId);
}
return found;
}