-
Find Control By Name
I need a function that returns a control within a form based on a string name. I've tried Jim's method here, but then found out that it will not work with SplitContainers. Therefore, I feel like I need to use a recursive function, or maybe a stack. I've tried many different examples online, but I can't seem to get any to work. This is the code for the latest try, as taken from here:
Code:
Public Function FindControlRecursively(ByVal ParentControl As Control, ByVal ControlTobeSearched As String) As Control
Dim FoundControl As New Control
For Each CurrentControl As Control In ParentControl.Controls
If (CurrentControl.Name = ControlTobeSearched) Then
FoundControl = CurrentControl
Exit For
End If
If (CurrentControl.HasChildren) Then
FoundControl = FindControlRecursively(CurrentControl, ControlTobeSearched)
End If
Next
Return FoundControl
End Function
Note that the above code only seems to return a blank control.
-
Re: Find Control By Name
Just parse the split container also while looping.
Code:
For Each ctrl In Me.SplitContainer.Panel1.Controls
-
Re: Find Control By Name
Try this:
Code:
Public Function FindControlRecursively(ByVal ParentControl As Control, ByVal ControlTobeSearched As String) As Control
Dim FoundControl As Control = Nothing
For Each CurrentControl As Control In ParentControl.Controls
If CurrentControl.Name.ToLower() = ControlTobeSearched.ToLower() Then
FoundControl = CurrentControl
ElseIf CurrentControl.HasChildren Then
FoundControl = FindControlRecursively(CurrentControl, ControlTobeSearched)
End If
If FoundControl IsNot Nothing Then
Exit For
End If
Next
Return FoundControl
End Function