|
|
Title | Invoke an object's method by name in Visual Basic .NET |
Description | This example shows how to invoke an object's method by name in Visual Basic .NET. |
Keywords | invoke, callbyname, call method by name, Visual Basic .NET, VB.NET |
Categories | Software Engineering |
|
|
You can use the CallByName function to invoke an object's method. When you click this example's Invoke button, the program uses the following code to call the method named in the text box. For example, type Method1 or Method2 in the text box and click the button. If you type something else, you'll get an error.
|
|
Imports Microsoft.VisualBasic.CallType
Public Class Form1
' Invoke a method by name.
Private Sub btnInvoke_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnInvoke.Click
Try
CallByName(Me, txtMethodName.Text, Method, _
Nothing)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
' The public methods to invoke.
Public Sub Method1()
MessageBox.Show("This is Method 1")
End Sub
Public Sub Method2()
MessageBox.Show("This is Method 2")
End Sub
End Class
|
|
Note that the first parameter passed to CallByName is the object whose method should be invoked. As far as I know, CallByName won't let you invoke a routine defined in a code module (i.e. not in a class).
(You can also use reflection to invoke a method by name but it's more work.)
|
|
|
|
|
|