[RESOLVED] [2005] ListBox RightClick Selects
Hey there :wave:
I'm using this code to select an item in a ListBox when a user right clicks on it
VB Code:
Private Sub listOnline_MouseDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles listOnline.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim mouseY As Integer = listOnline.PointToClient(Windows.Forms.Cursor.Position).Y
Dim itemIndex As Integer = (mouseY \ listOnline.ItemHeight) - listOnline.TopIndex
listOnline.SelectedIndex = itemIndex
listOnline.ContextMenuStrip = blockMenu
Dim myString As String = listOnline.SelectedItem
Dim mySplit(2) As String
mySplit = Split(myString, " - ")
If InStr(mySplit(0), "ยค") Then
Block.Text = "Unblock: " & mySplit(2)
Else
Block.Text = "Block: " & mySplit(2)
End If
End If
End Sub
It works great....but....my list is bigger than the container so a scrollbar appears, I can only rightclick select things that appear in the ListBox when the scrollbar is all the way up, if I scroll down and try to rightclick select something it wont work. It basically selects the "wrong" item....the item that would be in that place if the scrollbar was all the way up....
It probably has something to do with this:
VB Code:
Dim itemIndex As Integer = (mouseY \ listOnline.ItemHeight) - listOnline.TopIndex
.....what could I use instead to make it work?
Re: [2005] ListBox RightClick Selects
Use this...
Code:
ListBox1.IndexFromPoint(New Point(e.X, e.Y))
in your MouseDown handler to get the correct item that you are over.
Re: [2005] ListBox RightClick Selects
You should use the IndexFromPoint method to determine the index of the item at the point that was clicked. That will work regardless of whether or how far the control is scrolled. Here's a quote from the help topic:
Quote:
You can use this method to determine which item within the list is selected when a user right-clicks over the ListBox.
Re: [2005] ListBox RightClick Selects
I need to consume more caffeine it would appear. :)