Recursive Find Control

S

shapper

Hello,

I need a recursive find control down the control tree.

I have created some code and also found a few examples online.

However, I am having some problem to decide which one to use because I
think if this code is not well done it can slow my web site.

Any advice about these codes would be great or even point me to better
code:

Code 1

Public Shared Function FindControl(Of T As Class)(ByVal Controls As
System.Web.UI.ControlCollection) As T
Dim found As T = Nothing
If Controls IsNot Nothing AndAlso Controls.Count > 0 Then
For i As Integer = 0 To Controls.Count - 1
If TypeOf Controls(i) Is T Then
found = TryCast(Controls(i), T)
Exit For
Else
found = FindControl(Of T)(Controls(i).Controls)
End If
Next
End If
Return found
End Function


Code 2

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



Code 3

Public Delegate Function ControlWalkerMatcher(ByVal control As
Control) As Boolean
Public Shared Function ControlWalker(ByVal control As Control,
ByVal matcher As ControlWalkerMatcher) As Control()

Dim parent As New ArrayList()
If matcher(control) Then
parent.Add(control)
End If

For i As Integer = 0 To control.Controls.Count - 1
Dim child As Control() = ControlWalker(control.Controls(i),
matcher)
If child.Length > 0 Then
parent.AddRange(child)
End If
Next i
Return DirectCast(parent.ToArray(GetType(Control)), Control())
End Function

Thanks,

Miguel
 
B

bruce barker

all three do different things.

1. returns the first control of type specifed, even if more than one match
2. returns the first control with matching id, even if more than one match
3. returns an array of all controls matching the delegate criteria

1 & 2 are slightly faster as they quit on the first match, though the
delegate solution could be modified to return first match instead of all.

-- bruce (sqlwork.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top