Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleInvoke an object's method by name in Visual Basic .NET
DescriptionThis example shows how to invoke an object's method by name in Visual Basic .NET.
Keywordsinvoke, callbyname, call method by name, Visual Basic .NET, VB.NET
CategoriesSoftware 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.)

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated