Created On:
16/04/2007
Author:
Aaron Robson
Tags:
c#, asp.net

Recursive FindControl Simplified

Update: 23 April 07 - The code as outlined below doesn't work correctly, see this new post for details.

Now this is either Brave or Stupid, but I couldn't resist simplifying J. Michael's code. The bravery (or stupidity) is the fact that I haven't actually tried it out in Visual Studio... :). Often when I have an impulsive bright idea, it's stupid, so time will tell...

Steve Smith started this off, and he was feeling bereft of link love, so there ya go Steve :)

public T FindControl<T>(string id) where T : Control
{
return FindControl<T>(Page, id);
}

public static T FindControl<T>(Control startingControl, string id) where T : Control
{
T found = null;

foreach (Control activeControl in startingControl.Controls)
{
found = activeControl as T;

if (found == null)
{
found = FindControl<T>(activeControl, id);
}
else if (string.Compare(id, found.ID, true) != 0)
{
found = null;
}

if (found != null)
{
break;
}
}

return found;
}

Comments

J. Michael Palermo IV -
Code looks good to me! (and it works too!)
Aaron -
Hehehe, cheers! Pleased about that - I hereby award myself the bravery award :)
Steele Price -
That code breaks when you are trying to find startingControl itself,
Aaron -
When you say breaks, do you mean returns null ? I implemented the functionality of the original code AFAIK...
Steele Price -
It never checks Starting Control, so if in fact the control you are looking for happens to be startingControl, and not something contained in it, then it returns null which is IMO, wrong. It was also missing in the original too which I corrected for the VB side. I also found that it was helpful to test for id being empty, wierd things will match (like a masterpage) if they are not excluded from the string.compare. Nce work on the rest thogh.
Aaron -
Actually, this code is entirely wrong (as is the code its based on) ! I've updated the post with a link to the new version.