1
votes

In my vb.net app, I've got a list box that contains a bunch of email addresses.

There's a context menu on the list box with view contact, modify and remove options.

I'm currently stuck on how to determine which item in listbox1.items the user has right-clicked for use in the context menu actions.... So say for example a user right clicks '[email protected]' and clicks remove I then need to say

   listbox1.items.remove(THEITEMTHATWASRIGHTCLICKED)

But how would I determine THEITEMTHATWASRIGHTCLICKED?

I tried...

 itemthatwasrightclicked = listbox1.SelectedIndex

But if I right click on an item before left-clicking, I get a returned index of -1. If I left click the item to select it first and then right click I get the correct index returned, so it seems that if a user right clicks without first left clicking, the item isn't selected as such.

I'm at a loss and any help is appreciated!

I feel like this should be something simple.

Thanks in advance! :)

1

1 Answers

2
votes

The listbox class provides a method for this in the MSDN. You will want to use the IndexFromPoint(Point) method. When this method is called it returns the index for the item in the list box found at the coordinates of the Point specified. You will want to capture the coordinates of the right click event by implementing this within the MouseDown event of the ListBox.

In its most basic form, the code for this would be as follows.

Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
    If e.Button = MouseButtons.Right Then
        ListBox1.SelectedIndex = ListBox1.IndexFromPoint(e.X, e.Y)
    End If
End Sub