Is there a simpler way to do this?

G

Guest

I wish to dynamically create a context menu of uncertain length, the
uncertainty depending on the number of records in a database. As of right
now what I am doing is adding a number of instances of menuItem to the
context menu cm1. Each instance, when added, is linked to the handler
menuItemMain_click.

Here's menuItemMain_Click. This seems to work but is there a simpler way to
identify the index of the clicked menu item?

---------------------------------------
Private Sub menuItemMain_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
Dim i As Integer
For i = 0 To cm1.MenuItems.Count - 1
If sender Is cm1.MenuItems(i) Then
MsgBox("Here I am " & i.ToString)
Exit Sub
End If
Next
End Sub
 
G

Guest

Perfect! Thanks!

AMercer said:
I think
CType(sender, MenuItem).Index
is the zero based index of sender in the parent menu. No first hand
experience, but it sounds like what you need.
 
R

rampabbaraju

Try to use the tag property of the MenuItem class to uniquely identify
your menu item. Then you don't need to loop through all your menu items
to find which one raised the click event.
 
G

Guest

Try to use the tag property of the MenuItem class to uniquely identify
your menu item.

MenuItem doesn't have a tag property, at least as of .net fw 1.1 sp1. It
should - maybe in v2?
 
G

Guest

Dear 'AMercer'

Thanks for the inspiration. At the risk of bragging, you don't need to wait
for 2.0 for a 'tag'. You can make your own!

First declare a class.

Public Class MutantMenuItem
Inherits MenuItem

Dim i As Integer

Public Property ID() As Integer
Get
Return i
End Get
Set(ByVal Value As Integer)
i = Value
End Set
End Property

End Class

Then add whatever properties you need (in my case, all I needed was an
integer key) and use it as you would any menu item. Then when you get to the
event handler, retrieve the ID value with the call: <local variable> =
CType(sender, MutantMenuItem).ID

(Maybe I still have a few brain cells left. ;-)
 
S

Scott Coonce

Public Class MutantMenuItem
Inherits MenuItem

Dim i As Integer

Public Property ID() As Integer
Get
Return i
End Get
Set(ByVal Value As Integer)
i = Value
End Set
End Property

End Class

Just to expand: screw the ID as Integer, set the _object_ you want as the
item:

Public Class MutantMenuItem
Inherits MenuItem

Dim mut as Mutant
Public Property Mut() As Mutant
Get
Return mut
End Get
Set(ByVal Value As Mutant)
mut = Value
End Set
End Property
End Class

scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top