Hi Mike,
I have two routines that allow you to either open a form if the name of
the form is stored in a variable, or call a function (or subroutine) if
the name of the function is stored in a variable:
Note - The functions that are being called are actually methods of a
class, and the routine to call these functions is stored in the same
class. So, this code will need to be modified if you can't arrange
your application so that all possible functions that get called in this
manor are located in the same class. Most of the time names of
functions aren't stored in variables. I happen to build a Menu Strip
on the fly based on information in a database. 99% of the time when a
menu item is clicked, I open a form (using the below code). However,
there are a couple of situations when I need to call a function when a
menu item is clicked.
Here's the class for calling a function stored in a variable:
Imports System.Reflection
Public Class CallFunctions
Public Function ExecuteMethods(ByVal prmMethodName As String,
Optional ByVal prmParams() As Object = Nothing) As Object
'Create a type object and store the type of the object passed
Dim objType As Type = Me.GetType
'Declare a MethodInfo object to store the Methods of the class
Dim objMethodInfo As MethodInfo
'Get the MethodInfo for the current class. Binding Flags are
specified to get the public and private Methods of this class. When
'Public or Non-Public is specified in the BindingFlags, it is
also necessary to specify Static or Instance
objMethodInfo = objType.GetMethod(prmMethodName,
BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static Or
BindingFlags.Instance)
Return objMethodInfo.Invoke(Me, prmParams)
End Function
Public Sub SubRoutine1()
.......Your code here
End Sub
Public Sub SubRoutine2()
......Your code here
End Sub
Public Function(prmArgument1 as String) As String
.....Your code here
End Sub
End Class
You would use this class in your code as follows:
Dim cf As New CallFunctions
Call cf.ExecuteMethods(variablename, array of parameters)
You can leave the second argument empty if you aren't passing any
parameters.
On the other hand, if you need to open a form and the name of the form
is stored in a variable, you can do this:
Public Sub OpenForm(prmFormName As String)
Dim app As System.Reflection.Assembly =
System.Reflection.Assembly.GetExecutingAssembly()
Try
Dim frm As Form = app.CreateInstance("Namespace." &
prmFormName, True)
frm.Show()
Catch e as Exception
End try
End Sub
You need to substitute "Namespace." with your namespace (and the
period).
Please note that I cannot take full credit for these routines. I have
found most of this in other places on the Internet and I modified them
slightly for my use.
Hope this helps.
Steve