How to call a function when I only have the functionname as a string

This is a simplified version of my problem so please dont ask why I do
it this way!

I want to create an array of a user-defined structure. The structure
contains a control and a functionname. So something like below.

MyArray = {(control1, FunctionName1),
(control2, FunctionName2),
(control3, FunctionName3), ... }

Now I want to iterate through the array and call the related function
if the control is enabled:

for each Structure in MyArray
  if Structure.control.enabled then
      Call Structure.FunctionName   'DOES NOT WORK
  end if
next

But how do I call a function just specified by its name? Can I use Eval
or do I need to specify a reference to the function in the structure
instead of the functionname?
3895Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
Here is something that I use for form methods:

  Imports App = System.Windows.Forms.Application
  Imports System.Reflection

  Public Class FormMethods

    Public Function GetMethod(ByVal formName As String, ByVal method As String) As MethodInfo

      Try

        For Each methodCurrent As MethodInfo In Type.GetType(formName).GetMethods()

          If methodCurrent.Name.Equals(method) Then
            Return methodCurrent
          End If

        Next

      Catch ex As Exception

        MessageBox.Show(ex.ToString())

      End Try

    End Function   'GetMethod

  End Class


Sample usage:
Dim method As System.Reflection.MethodInfo = FormMethods.GetMethod("Form1", "GetName")
method.Invoke(Nothing, New Object() {})

Bob
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
If the function is public then you can also use the CallByName() function:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vafctcallbynamefunction.asp

Basic example...

Public Class Form1
    ...

    Pubilc Sub Button1_Click(...) Handles Button1.Click
        Dim s As String = CallByName(Me, "Foo", CallType.Method)
        MsgBox(s)
    End Sub

    Public Function Foo() As String
        Return "Foo"
    End Function

End Class

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
3895Author Commented:
Both answer is exactly what I wanted! The CallByName function seems to be the most simple. Before I split the points between you, I would like to ask the following:

A problem by calling functions this way is that I can not check for misspelled functionnames at design-time, and thus can get runtime-errors. So instead of having the functionname in my structure, could I have something like a reference to the function (maybe AddressOf functionname)? This way I would avoid runtime errors! But how do I execute the function by reference?
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
If you are not sure if the function name is correct then how could you possibly get a correct reference?   ;)

A function reference in .Net is called a Delegate by the way...
3895Author Commented:
I know what my functionname is but if I type it in my structure as a string, there is a chance that I misspell. I will not discover the misspell until I get a runtime error telling me that the function does not exist. If I use a delegate the program will not compile when I try to reference a misspelled function. Isn't taht correct???
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
Bottom line is if you are using a STRING to store the name of the function then you will not know if it is mispelled until runtime.  You will just have to catch the exception with a Try...Catch block.
3895Author Commented:
I found a solution to call a function by reference. This way I catch misspelled functionnames at compile-time.

Public Class Form1
    Inherits System.Windows.Forms.Form  

    Delegate Sub MethodDelegate()

    Public Structure Test
        public mControl As Control
        Public mDelegate As MethodDelegate

        Public Sub New(ByVal control As Control, ByVal methodDelagate As MethodDelegate)
            mControl = control
            mDelegate = methodDelagate
        End Sub
   End Structure

   Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Dim lTest as new Test(textbox1, New myMethodDelegate(AddressOf function1)) 'function1 has to exist. Otherwise compile-error!
      lTest.mDelegate.Invoke() 'This calls function1
   End sub

   Private Sub function1
      msgbox "Function call"
   End sub

End class

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.