Menu for Listbox

ImDaFrEaK

Well-known member
Joined
Jan 7, 2006
Messages
416
Location
California
Programming Experience
5-10
Ok, here is the jist of it. I want to use the Mouse Right Click to select a line of text in my listbox. That's task 1.

Task 2, I then want to display a Menu in which I will use to make changes to the selected item.

if ListBox has the following

I heart you.mp3
Money Money.mp3
Whatever song.mp3

and I Right Click on Money Money.mp3 I want it selected and a menu to pop up for it. You see this all the time in real world apps, why I can't figure out how to do this or find any help on it is beyond me. Thanks
 
Hi, The listbox exposes a 'IndexFromPoint' Method so in your listbox 'OnMouseDown' event input the following...

VB.NET:
If e.Button = MouseButtons.Right Then
Dim lb As ListBox = CType(sender, ListBox)
Dim pt As New Point(e.X, e.Y)
Dim index As Integer = lb.IndexFromPoint(pt)
lb.SelectedIndex = index
Me.(the name of your contextmenu).Show(Me.(the name of your listbox), pt)
End If

That will handle the the selecting of the item in your listbox on a right click.
The second point....

Place a contextmenu onto your form from the toolbox. Then Click on it in the component tray and at the top of your form it will say 'TypeHere' type in the menu's you want to display on right click. Then double click the menu item to get an event handler for this menu item.
 
better assign the contextmenu to the listbox, use mousedown to set the index even for right-mouse, then handle the request in menuitem click:
VB.NET:
Private Sub ListBox_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox.MouseDown
  ListBox.SelectedIndex = ListBox.IndexFromPoint(New Point(e.X, e.Y))
End Sub
 
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click
  If ListBox.SelectedIndex <> -1 Then
    'do something
    MsgBox(ListBox.Items(ListBox.SelectedIndex))
  End If
End Sub
 
vis781, what on earth are you talking about???
the contextmenu is positioned exactly from the mouse right-click position.
 
Thanks tons guys... That did the trick, I really appreciate both versions too b/c it helps me understand better what's going on. YOu guys are great. :)
 
Quite right JohnH I'm talking rubbish. However i would'nt go so far as to say that your way is 'better' There are many ways to accomplish goals in vb.net.
 
Back
Top