Results 1 to 3 of 3

Thread: Find Control By Name

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2010
    Location
    Huntsville, AL
    Posts
    62

    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.

  2. #2
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Find Control By Name

    Just parse the split container also while looping.

    Code:
            For Each ctrl In Me.SplitContainer.Panel1.Controls
    Last edited by ident; Sep 8th, 2011 at 03:06 PM.

  3. #3
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,289

    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
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width