Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get control by name using reflection

Tip of the Day

Get control by name using reflection

by  chrissie1  Posted    (Edited  )
Getting a control by name using reflection
Found it here

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=10&txtCodeId=3255&txtForceRefresh=2192005168627679

Code:
Public Function GetControlByName(ByVal Name As String) As Control

        'now, why would I put a "_" in front of the name? 
        Dim info As System.Reflection.FieldInfo = Me.GetType().GetField("_" & Name, _
        System.Reflection.BindingFlags.NonPublic Or _
        System.Reflection.BindingFlags.Instance Or _
        System.Reflection.BindingFlags.Public Or _
        System.Reflection.BindingFlags.IgnoreCase)

        If info Is Nothing Then Return Nothing
        Dim o As Object = info.GetValue(Me)
        Return o

    End Function

SBendBuckeye sent me a mail to add the following to the faq for the following reason. "I found your FAQ a couple weeks ago but needed to be able to call it from a standard module so I tweaked it to make it Public Shared."

So here we have it
Code:
Imports System.Windows.Forms

Public Class ReflectionInfo
    Public Shared Function GetControlByName(ByVal Name As String, _
                                            ByVal CurrentForm As Form) As Control
        Dim info As System.Reflection.FieldInfo = _
            CurrentForm.GetType().GetField("_" & Name, _
                System.Reflection.BindingFlags.NonPublic Or _
                System.Reflection.BindingFlags.Instance Or _
                System.Reflection.BindingFlags.Public Or _
                System.Reflection.BindingFlags.IgnoreCase)
        If info Is Nothing Then
            Return Nothing
        Else
            Return CType(info.GetValue(CurrentForm), Control)
        End If
    End Function
End Class
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top