Get a control handle by control name

adwaitjoshi

Active member
Joined
Dec 29, 2005
Messages
38
Programming Experience
1-3
I wish to set focus to a control (may be textbox, combobox, listbox etc) in a form. I wish to do this by the control name so basically something like

GetControl(ControlName).Focus()

is there a function to do that?
 
Controls are Windows Forms elements. Moved to the Windows Forms forum. Please post to the most appropriate forum.

There is no simple in-built way to do that. You could write your own GetControlByName method and call that. The best way to do that would be to use the GetNextControl method of the form in a loop until you find one with a Name property that matches the value you're looking for. Note that controls created at run time will have an empty Name property unless you have specifically set it, and they are not necessarily unique.
 
Reflection allows you to, amongst other things, query a type to see what members it has and then access one of those members by name via a string, which is exactly what you want to do. This is how you would do it using reflection:
VB.NET:
    Private Function FocusControlByName(ByVal controlName As String) As Boolean
        Dim myType As Type = Me.GetType()
        Dim myFieldInfo As Reflection.FieldInfo = myType.GetField(controlName)

        If myFieldInfo Is Nothing Then
            'No member variable exists with the specified name.
            Return False
        Else
            Dim myObject As Object = myFieldInfo.GetValue(Me)

            If TypeOf myObject Is Control Then
                CType(myObject, Control).Focus()
                Return True
            Else
                'The specified variable is not a control.
                Return False
            End If
        End If
    End Function
I haven't used reflection a lot myself so I'm not sure, but I would guess that this would only work if you have declared the controls as public or friend members. Private members cannot be seen from outside the class itself so I doubt that they are accessible to reflection.
 
Back
Top