INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Tip of the Day

Get control by name using reflection by chrissie1
Posted: 19 Feb 05 (Edited 18 May 05)

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

Back to Visual Basic (Microsoft) VB.NET FAQ Index
Back to Visual Basic (Microsoft) VB.NET Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close