dynamic context menus

fotini

Active member
Joined
Jun 3, 2003
Messages
39
Im trying to work with dynamic context menus in VB.NET and running into
what seems to be a very simple but very annoying problem.
Say my user has created a list of "names". Could be 1,2,5.. or 20 names. I
don t know at design time. Now I want to create a context menu with these
names as the menu text. Creating the menus is a piece of cake but
determining what name the user actually clicked seems to be impossible.
When you create the menu you either pass it a menuitem class or use
AddressOf to point it to a Sub.
Idealy Id like all the menus to point to a single Sub and use a Select
Case or something to dertermine what was selected but as I said above I
cant figure out how to pass the from the ContextMenu to the sub.
The only way I can see how to do this is to create 20 or so shell event
handlers at design time for the menu items and then use IFs to match them
up to the contextmenu at run time.
Would look something list this

Public Sub DoWork (nameIndex as int32)
Actually process the context menu selected
End Sub

Private Sub ContextMenu1_Popup
dim intNumOfNames as Int32 = names.count
if intNumOfNames > 0 then
CM1.MenuItem.Add(names.item(1).ToString, AddressOf (MenuName1))
end if
if intNumOfNames > 1 then
CM1.MenuItem.Add(names.item(2).ToString, AddressOf (MenuName2))
end if
if intNumOfNames > 2 then
CM1.MenuItem.Add(names.item(3).ToString, AddressOf (MenuName3))
end if
Yadda Yadda Yadda
End Sub

Protected Sub MenuName1 (byval sender as yadda)
DoWork (1)
End Sub
Protected Sub MenuName2 (byval sender as yadda)
DoWork (2)
End Sub
Protected Sub MenuName3 (byval sender as yadda)
DoWork (3)
End Sub
And so forth and so forth

This has two drawbacks. One it creates a ceiling for the number of names the
user can be working with and secondly its damm messy not to mention
inefficent code.

What Im trying to do is really simply. Determine what menu/name the user
selected. Can any one offer a brighter idea? And please dont say combo or
list box or Ill just cry.

fotini
 
try the following snippet and let me know if it helps.

all Ive done for the array is in the declaration section
[VB]
Dim names() As String = {"james", "steve", "dave", "fred"}
[/VB]

and the following after the forms designer code

[VB]
Public Sub DoWork(ByVal nameIndex As Int32)
Actually process the context menu selected

End Sub


Private Sub ContextMenu1_Popup(ByVal sender As Object, ByVal e As System.EventArgs) Handles CM1.Popup
Dim intNumOfNames As Int32 = names.Length

CM1.MenuItems.Clear()
Dim m As String
For Each m In names
CM1.MenuItems.Add(m, AddressOf MenuHandler)
Next


End Sub


Protected Sub MenuHandler(ByVal sender As Object, ByVal e As System.EventArgs)

Dim m As MenuItem
m = DirectCast(sender, MenuItem)

DoWork(m.Index)
End Sub
[/VB]
 
Back
Top