.Net FindControlRecursive

Posted in Tutorials

You can probably find this function all over the internet, but I like to keep it handy anyway. It loops through a particular control and its children and its children's children and so-on to find a given ID.

In VB.net:

Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control If root.ID = id Then Return root End If For Each c As Control In root.Controls Dim t As Control = FindControlRecursive(c, id) If t IsNot Nothing Then Return t End If Next Return Nothing End Function

Also in C#:

private Control FindControlRecursive(Control root, string id) { if (root.ID == id) { return root; } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; }