Determine clicked column in ListView

后端 未结 4 1904
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 12:08

I need to get the column clicked in a ListView in C#

I have some sample code from How to determine the clicked column index in a Listview but I\'m not sure how I sho

相关标签:
4条回答
  • 2020-12-14 12:25

    The ListView control has a HitTest method. You give it the x- and y-coordinates of the mouse click event, and it gives you an object that tells you the row (list view item) and column (list view subitem) at that point.

    0 讨论(0)
  • 2020-12-14 12:44

    Jeez, everyone's too lazy to post code. There are three steps to the process:

    1. Get the mouse position using Control.MousePosition and convert to client coordinates.
    2. Call the HitTest function to find what the mouse is pointing to. This returns an object with lots of information except the actual column number so...
    3. Search the subitems array using IndexOf to find the column number.

    Here's the code:

    private void listViewMasterVolt_DoubleClick(object sender, EventArgs e)
    {
        Point mousePosition = myListView.PointToClient(Control.MousePosition);
        ListViewHitTestInfo hit = myListView.HitTest(mousePosition);
        int columnindex = hit.Item.SubItems.IndexOf(hit.SubItem);
    }
    
    0 讨论(0)
  • 2020-12-14 12:50

    This is VB.NET code, but the objects should be the same.

    Private LVUsersLastHit As Point
        Private Sub lvUsers_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvUsers.MouseUp
            Me.LVUsersLastHit = e.Location
        End Sub
        Private Sub LvUsers_Doubleclick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvUsers.DoubleClick
            Dim HTI As ListViewHitTestInfo = Me.lvUsers.HitTest(Me.LVUsersLastHit)
            If HTI.Item Is Nothing OrElse HTI.SubItem Is Nothing Then Exit Sub 'nothing was dblclicked
            MsgBox("doubleClicked the " & HTI.Item.ToString & " Item  on the " & HTI.SubItem.ToString & " sub Item")
        End Sub
    
    0 讨论(0)
  • 2020-12-14 12:50

    the e.Column actually holds the index

        private void lv_ColumnClick(object sender, ColumnClickEventArgs e)
        {            
            Int32 colIndex = Convert.ToInt32(e.Column.ToString());
            lv.Columns[colIndex].Text = "new text";
    
        }
    
    0 讨论(0)
提交回复
热议问题