Create Event handles dynamically using variable as the actions

126 Views Asked by At

I'm try to improve our dynamic reporting system. I would like to add event handle to the object I've dynamically created on the form. One of the functions of this would be to populate a listbox from what was selected in the first listbox. i.e. The user select a town and the second listbox is populated by all the people living in that town.

The objectaction and objectactionfunction would be stored in a SQL table in the system. I would also like to store the objectactionfunction code in the table and dynamically create it at runtime. I've been looking into CodeDOM. Am I looking in the right direction. Pseudocode below

dim objectaction as string
dim objectactionfunction as string
objectaction = "LostFocus"
objectactionfunction =" "

addHandler textbox1.objectaction, addressof objectactionfunction
1

There are 1 best solutions below

3
On BEST ANSWER

Here is an example of using Reflection to register an event handler using Strings to specify the event name and the event handler name:

Imports System.Reflection

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim eventName = "Leave"
        Dim methodName = "TextBox1_Leave"

        Dim targetType = TextBox1.GetType()
        Dim [event] = targetType.GetEvent(eventName)
        Dim eventHandlerType = [event].EventHandlerType
        Dim eventHandlerMethod = Me.GetType().GetMethod(methodName, BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim eventHandlerDelegate = eventHandlerMethod.CreateDelegate(eventHandlerType, Me)

        [event].AddEventHandler(TextBox1, eventHandlerDelegate)
    End Sub

    Private Sub TextBox1_Leave(sender As Object, e As EventArgs)
        MessageBox.Show("Success!")
    End Sub

End Class

As I said in my comment, the code is rather verbose but that's the way it goes. Here's an extension method that you can use to write code once and use it wherever you like:

Imports System.Reflection
Imports System.Runtime.CompilerServices

Public Module ObjectExtensions

    <Extension>
    Public Sub AddEventHandler(source As Object,
                               eventName As String,
                               eventHandlerName As String,
                               eventHandlerSource As Object)
        Dim [event] = source.GetType().GetEvent(eventName)
        Dim eventHandlerMethod = eventHandlerSource.GetType().GetMethod(eventHandlerName, BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim eventHandlerDelegate = eventHandlerMethod.CreateDelegate([event].EventHandlerType, eventHandlerSource)

        [event].AddEventHandler(source, eventHandlerDelegate)
    End Sub

End Module

Sample usage:

Dim eventName = "Leave"
Dim methodName = "TextBox1_Leave"

TextBox1.AddEventHandler(eventName, methodName, Me)