How to access a method via its declaration name using reflection 

I could spend a million words explaining it, or you could look at the code.

I encountered an interesting forum post where the person was storing the event-handler-name in a database as a string,for certain events. They needed a way of identifying(from a string) which method to assign to their object's events.

I created the following example that uses reflection to identify the correct routine by accessing its MethodInfo.Name property, later it converts this methodinfo into a delegate, and then into an eventhandler. It then can be dynamically added as the event handler for a controls event.

Keep in mind, as with coding always, if not used right, you will of course get errors.

  • Create a new test project
  • Double-Click Form1
  • Delete all code you see there.
  • Paste the following code into form1
'Option Strict is always recommended
Option Strict On
'Import Reflection
Imports System.Reflection
Public Class Form1
    'Create a menustrip for the form
    WithEvents MenuStrip1 As New MenuStrip With {.Parent = Me}
    'create a button to test our adder
    WithEvents Button1 As New Button With {.Parent = Me, .Top = 100}
    'Create a new instance of the MyMethods Class
    Dim ObjectAdder As New MyMethods
    'Be sure to create a matching button for this button event
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Call the AddMenuItem sub from your instance of MyMethods
        'Tell the AddMenuItem method the name of your menustrip, the caption of the menuitem, and the name of the sub
        'in the MyMethods class that you want to become its event handler
        ObjectAdder.AddMenuItem(Me.MenuStrip1, "Are You Out There???", "SubC")
    End Sub
End Class
  • Add a new class to your project.
  • Delete the default code from the new class
  • Paste the following code into the new class
Option Strict On
Public Class MyMethods
    'Pre-Defined Subs
    Public Sub SubA(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("Hello, I am SubA, and I am your dynamic event handler.")
    End Sub
    Public Sub SubB(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("Hello, I am SubB, and I am your dynamic event handler.")
    End Sub
    Public Sub SubC(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("Hello, I am SubC, and I am your dynamic event handler.")
    End Sub
    Public Sub SubD(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("Hello, I am SubD, and I am your dynamic event handler.")
    End Sub
    Public Sub AddMenuItem(ByVal Menu As MenuStrip, ByVal MenuText As String, ByVal MethodName As String)
        'Create the new toolstripbutton
        Dim ToolStripButton As New ToolStripButton
        'Set the toolstrip button's caption
        ToolStripButton.Text = MenuText
        'Iterate through a collection of each methodinfo in the MyMethods class, using reflection
        For Each Method As MethodInfo In GetType(MyMethods).GetMethods
            'If we find one with a name that matches the specified name
            'then we create an event handler from the methodinfo
            If Method.Name = MethodName Then
                'Add that handler to the toolstripbutton click event
                AddHandler ToolStripButton.Click, EventHandlerFromMI(Method)
                'end iteration
                Exit For
            End If
        'add the toolstrip item to the specified menu
    End Sub
    Public Function EventHandlerFromMI(ByVal MethodInfo As System.Reflection.MethodInfo) As EventHandler
        'Create a delegate from the methodinfo
        Dim ConvertThisDelegate As System.Delegate = _
                System.Delegate.CreateDelegate(GetType(eventhandler), Nothing, MethodInfo, False)
        'convert the delegate into an eventhandler, and output it from the function
        Return DirectCast(ConvertThisDelegate, EventHandler)
    End Function
End Class

  • Run the project and see the results speak for themself!


Special thanks to John.

Please check out my other Technet Wiki articles!