Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Dynamic Context Menus

I am stuck with context menus and seem to be spinning my wheels.

I want to build a context menu in code, then perform actions based on the item selected.

I could do something like
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ContextMenu1 = New System.Windows.Forms.ContextMenu
Dim MenuItem1 = New System.Windows.Forms.MenuItem
Dim MenuItem2 = New System.Windows.Forms.MenuItem

ContextMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {MenuItem1, MenuItem2})
MenuItem1.Index = 0
MenuItem1.Text = "MenuText1"
MenuItem2.Index = 1
MenuItem2.Text = "MenuText2"
Button1.ContextMenu = ContextMenu1
End Sub

I would prefer to read each of the menu items ("MenuText1" and "MenuText2")from a config file as they change quite a bit and I would prefer to not hard code them.

To handle the click, I would need something like this:

Private Sub MenuItemSelected_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuitem1.click, MenuItem2.click
' code to handle event goes here...
' prefer to figure out the index of the item clicked and process accordingly
End Sub

The problem is that the compiler does not know the MenuItem1.Click or MenuItem2.click events.

Someone suggested a way to do this in C earlier, it looks like it would work in C but I am not sure how to implement in VB.

Any help is appreciated
[1534 byte] By [No-e] at [2007-11-11 6:50:07]
# 1 Re: Dynamic Context Menus
When you create the context menu, you should add the line like this:

MM_ContextMenu.MenuItems.Add("A text you like", New System.EventHandler(AddressOf Me.MM_ContextMenu_Click))

Then create a new procedure like this:

Private Sub MM_ContextMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs)

.........Your code here............
End Sub

Hope it helps !
semidieu at 2007-11-11 21:50:00 >