Visual Basic Development Bookmark and Share   
 Home > Visual Basic Language > Is it possible to run a method by giving a it's name in string not by a referene?
 

Is it possible to run a method by giving a it's name in string not by a referene?

Is it possible to run a method by giving a it's name in string not by a referene?

Well that's basicaly it!

naurispunk  Tuesday, August 07, 2007 2:06 PM
Yes, search the board for "Reflection".

TaDa  Tuesday, August 07, 2007 3:36 PM
The easiest way is to use the CallByName function.

JohnWein  Tuesday, August 07, 2007 4:12 PM
JohnWein wrote:
The easiest way is to use the CallByName function.

I find out about more VB shortcuts in these forums!

In an effort to learn the underlying .Net way of doing things I've avoided the VisualBasic namespace as much as possible - perhaps this results in more work on my part, but it also gives a better understanding of whats actually going on. It would appear that the CallByName function wraps a number of reflection steps into a single call. Handy - but not very revealing.

Here is a simple example of using reflection to invoke a method on an object instance by method name.

First, assume the simple class Foo:

Code Snippet

Public Class Foo

Public Function HelloWorld1() As String

Return "Hello World - One"

End Function

Public Function HelloWorld2() As String

Return "Hello World - Two"

End Function

End Class

Now, with an instance of Foo created, here is the code to invoke a method by name on the instance:

Code Snippet

Dim f As New Foo

Dim methodName As String

Dim result As Object

methodName = "HelloWorld1"

result = GetType(Foo).GetMethod(methodName).Invoke(f, Nothing)

MessageBox.Show(result.ToString)

Hope that helps!

Reed Kimble  Tuesday, August 07, 2007 4:41 PM

Hi Antinsh,

Youcan pass string of method name to dynamically call method. We needto usethe Type.InvokeMember method. Here is a little example of what you are trying to do. Hope this helps.

Code Snippet

Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim d1 As Dispatch = New Dispatch("A")

Dim d2 As Dispatch = New Dispatch("B")

Dim d3 As Dispatch = New Dispatch("C")

d1.Execute()

d2.Execute()

d3.Execute()

Sub

Class Target

Public Sub A()

System.Windows.Forms.MessageBox.Show("This is method A.")

Sub

Public Sub B()

System.Windows.Forms.MessageBox.Show("This is method B.")

End Sub

Class

Dispatch

Private _targetMethod As String

Public Property TargetMethod() As String

Get

Return _targetMethod

End Get

Set(ByVal value As String)

_targetMethod = value

End Set

End Property

Public Sub New(ByVal targetMethod As String)

Me._targetMethod = targetMethod

End Sub

Public Sub Execute()

Dim t As Type = GetType(Target)

Try

t.InvokeMember(TargetMethod, BindingFlags.Instance Or BindingFlags.InvokeMethod Or BindingFlags.Public, Nothing, New Target(), Nothing)

Catch ex As MissingMethodException

System.Windows.Forms.MessageBox.Show("Could not find the supplied method." + Environment.NewLine + ex.Message)

End Try

End Sub

Class

Best regards,

Riquel_Dong  Friday, August 10, 2007 1:30 AM
Yes, search the board for "Reflection".

TaDa  Tuesday, August 07, 2007 3:36 PM

Hi,

I have been looking at the following commands etcetera, some of which I am confused by ( I must admit ).>>

  • AddHandler
  • AddressOf
  • WithEvents

I am not sure if one of them will also let you do what you are after doing?

Take a look at.>>

http://msdn2.microsoft.com/en-us/library/ms172880(VS.80).aspx

http://msdn2.microsoft.com/en-us/library/74wy9422(vs.80).aspx

http://msdn2.microsoft.com/en-us/library/stf7ebaz(vs.71).aspx

The only way I can see of doing it is to Call a Sub or Function based on the contents of the string.>>>>

Code Snippet

Private Sub whatever()

Dim myString As String = ""

If myString = "1" then Call Method1()

End Sub

Private Sub Method1()

End Sub

Regards,

S_DS

John Anthony Oliver  Tuesday, August 07, 2007 3:49 PM
The easiest way is to use the CallByName function.

JohnWein  Tuesday, August 07, 2007 4:12 PM
JohnWein wrote:
The easiest way is to use the CallByName function.

I find out about more VB shortcuts in these forums!

In an effort to learn the underlying .Net way of doing things I've avoided the VisualBasic namespace as much as possible - perhaps this results in more work on my part, but it also gives a better understanding of whats actually going on. It would appear that the CallByName function wraps a number of reflection steps into a single call. Handy - but not very revealing.

Here is a simple example of using reflection to invoke a method on an object instance by method name.

First, assume the simple class Foo:

Code Snippet

Public Class Foo

Public Function HelloWorld1() As String

Return "Hello World - One"

End Function

Public Function HelloWorld2() As String

Return "Hello World - Two"

End Function

End Class

Now, with an instance of Foo created, here is the code to invoke a method by name on the instance:

Code Snippet

Dim f As New Foo

Dim methodName As String

Dim result As Object

methodName = "HelloWorld1"

result = GetType(Foo).GetMethod(methodName).Invoke(f, Nothing)

MessageBox.Show(result.ToString)

Hope that helps!

Reed Kimble  Tuesday, August 07, 2007 4:41 PM

Hi rkimble.

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim f As New Foo

Dim methodName As String

Dim result As String = ""

methodName = "HelloWorld1"

result = GetType(Foo).GetMethod(methodName).Invoke(f, Nothing)

MessageBox.Show(result)

End Sub

End Class

Gives an "Object reference not set to an instance of an object" exception error in the highlighted line above.

Even with result as OBJECT.

Yes I did add your Foo CLASS code separately.

Regards,

S_DS

John Anthony Oliver  Tuesday, August 07, 2007 11:05 PM

Hi SDS,

Please check your code - this error indicates that the Class Foo does not contain a method named "HelloWorld1". You must have made an error when adding the Foo class to the project...

The code example I posted is correct. You can change the reflection line to the following if you like:

Code Snippet
result =
GetType(Form).GetProperty("Text").GetValue(Me, Nothing)

This will get the value of the Text property on the current form (and prove that this reflection works).

Best regards,

-Reed

Reed Kimble  Wednesday, August 08, 2007 3:38 PM

Hi Antinsh,

Youcan pass string of method name to dynamically call method. We needto usethe Type.InvokeMember method. Here is a little example of what you are trying to do. Hope this helps.

Code Snippet

Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim d1 As Dispatch = New Dispatch("A")

Dim d2 As Dispatch = New Dispatch("B")

Dim d3 As Dispatch = New Dispatch("C")

d1.Execute()

d2.Execute()

d3.Execute()

Sub

Class Target

Public Sub A()

System.Windows.Forms.MessageBox.Show("This is method A.")

Sub

Public Sub B()

System.Windows.Forms.MessageBox.Show("This is method B.")

End Sub

Class

Dispatch

Private _targetMethod As String

Public Property TargetMethod() As String

Get

Return _targetMethod

End Get

Set(ByVal value As String)

_targetMethod = value

End Set

End Property

Public Sub New(ByVal targetMethod As String)

Me._targetMethod = targetMethod

End Sub

Public Sub Execute()

Dim t As Type = GetType(Target)

Try

t.InvokeMember(TargetMethod, BindingFlags.Instance Or BindingFlags.InvokeMethod Or BindingFlags.Public, Nothing, New Target(), Nothing)

Catch ex As MissingMethodException

System.Windows.Forms.MessageBox.Show("Could not find the supplied method." + Environment.NewLine + ex.Message)

End Try

End Sub

Class

Best regards,

Riquel_Dong  Friday, August 10, 2007 1:30 AM

Thanx for help

CallByName works just fine!

Now I'm looking for a way to get a reference to a control by giving it's name as a string. But thats in another thread!

naurispunk  Wednesday, August 15, 2007 12:01 PM

You can use google to search for other answers

Custom Search

More Threads

• Can't figure out why this is generating a rather large Memory Leak.
• Sleep() Function VB2005 Equivalent
• ListBox control
• Programmatically Scrolling datagrid view
• I want to Total Values In The List View
• How to read and write to a file Asynchronously
• Is it possible to run an SQL statements against the content of the datatable?
• Reading CPU temperature
• in my project i need to format a multi line text box how to do
• Help on Extracting Information from HTML