Andy said:
I do mean procedure as in VB.NET procedure. I have looked at the
microsoft help on delegates and I am completely confused, and I was
wondering if you could possibly help further. The VB procedure name
that I need to run is currently read in to a string variable. I need to
associate this procedure name the menu handler.
Any help is appreciated as I have been at this for ages with no luck
Sorry for the delay.
Just to recap: we're dynamically creating menu items, and for each one
the information we are given includes the name of a procedure that
should be called when the menu item is clicked.
The first thing to consider is: the handler procedure for a menu item's
Click event must be a standard EventHandler; that is, it must look like
Sub Whatever ( _
sender As Object, _
e As EventArgs _
)
Do all the procedures already have this signature? They'll need to in
order to avoid us having to do messy late binding stuff. So let's
suppose we have this code in the form:
Private Sub MyClickEventHandler(ByVal sender As Object, _
ByVal e As EventArgs)
MsgBox("bar!")
End Sub
Now, when we create each menu item, create a delegate to call the
procedure to be called on click, and put it in the .Tag property:
' for example
Dim menuItemText As String = "Bar"
Dim eventProc As String = "MyClickEventHandler"
' create the menu item
Dim menuItem As New MenuItem(menuItemText)
' set whatever other properties...
' create the event handler delegate
Dim del As [Delegate] = _
[Delegate].CreateDelegate(GetType(EventHandler), _
Me, _
eventProc)
' strongly type it
Dim clickEventHandler As EventHandler = _
CType(del, EventHandler)
' assign it to the click event
AddHandler menuItem.Click, clickEventHandler
I agree this looks confusing if you havne't done anything like this
before. Just remember that a delegate is a special type that
encapsulates a method's *signature* (its parameters and return type),
and instances of delegate types are objects to be created and
manipulated like any other.