Alex Alex - 1 year ago 230 Question

Find listview column index using HitTestInfo

I'm looking to find the index of the column when I right click on the listview items using this code:

Private Sub Source_lvArticles_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Source_lvArticles.MouseDown
If e.Button = System.Windows.Forms.MouseButtons.Right Then
Sources_RightClickedCol = 0

Dim info As ListViewHitTestInfo = Source_lvArticles.HitTest(e.X, e.Y)
Sources_RightClickedCol = info.Location
End If
End Sub

I am able to find the text of the item that I'm right clicking (info.Subitem.Text), I just can't find its column index...

Answer Source

Unfortunately with the above code provided by Alex, there is a danger that if more than 1 sub item in a row contains the same text value then it will pick the first left most column index. A better way is just to copy the function below, which simply uses the mouse pointer X value and compares it to the columns right values, where X exceeds at which point we have the integer on a loop count:

Private Function GetColumnIndex(ByVal lvw As ListView, ByVal MouseX As _
Integer) As Integer

    Dim result As Integer = 0

    'Get the right and width pixel values of all the columns 
    Dim ColW As New List(Of Integer)
    Dim Index As Integer = 0

    For Each col As ColumnHeader In lvw.Columns
        Dim X As Integer = 0
        For i As Integer = 0 To ColW.Count - 1
            X += ColW(i)

        'Once you have the rightmost values of the columns 
        'just work out where X falls in between

        If MouseX <= X Then
            result = Index
            Exit For
        End If

        Index += 1


    Return result
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download