I’m needing to go through all the controls on a page, looking for a specific one. We’ve got a bunch of user controls, a masterpage, content panel, &c.
The basic idea is simple, but once I find the control I want, say five ‘layers’ in, the control is returned only one level.
I know I can do something cheesy like having a private variable and assigning the control to that down in the rabbit hole, but I figure there must be a more official method of doing this.
Also, is this what is called tail recursion?
We’re using the 3.5 framework.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim c As Control = getNamedControl(Page, "tb")
End Sub
Private Function getNamedControl(ByVal root As Control, ByVal theTarget As String) As Control
If root.Controls.Count < 1 Then
If Not IsNothing(root.ID) Then
If root.ID = theTarget Then
Return root
End If
End If
Else
For Each c As Control In root.Controls
If c.ID = theTarget Then
Return c
Else
getNamedControl(c, theTarget)
End If
Next
End If
End Function
The function will immediately return the control when it was found.
Are you sure that it’s a good idea to use a recursive function to find your controls? Especially if you use UserControls with the same ID in pages of the MasterPage’s ContentPages, you would probably find the wrong control. This is very error-prone.
Besides you are hard-wiring your UserControls with their pages with their MasterPage, what is the opposite of encapsulation and reusability.