VB.NET - Datagridview:获取单击列的索引

时间:2016-05-09 15:03:44

标签: vb.net datagridview

在VB.NET的DataGridView中,如何获取所单击列的索引,而不是具有所选单元格的索引。

我希望通过上下文菜单为用户提供右键单击列并隐藏它的选项。此代码为我提供了具有所选单元格的列的索引:

   Private Sub dataGridView1_ColumnHeaderMouseClick(sender As Object, ByVal e As DataGridViewCellMouseEventArgs) Handles dataGridView1.ColumnHeaderMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            currSelectedColIdx = e.ColumnIndex
            ContextMenuStrip1.Show()
        End If
    End Sub

编辑:当我通过属性窗口将contextmenu绑定到datagridview时,会出现问题。如果我解除绑定,代码可以正常工作。

2 个答案:

答案 0 :(得分:1)

您可以使用DataGridView的CellContextMenuStripNeeded事件。

Private Sub DataGridView1_CellContextMenuStripNeeded(sender As Object, e As DataGridViewCellContextMenuStripNeededEventArgs) Handles DataGridView1.CellContextMenuStripNeeded
    If e.RowIndex = -1 Then
        e.ContextMenuStrip = ContextMenuStrip1
        'e.ColumnIndex is the column than you right clicked on it.
    End If
End Sub

您可以使用以下代码获取列索引:e.ColumnIndex

答案 1 :(得分:0)

你的变量声明可能有问题" currSelectedColIdx" :

请尝试以下代码:

Private Sub DataGridView1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
    If e.Button = Windows.Forms.MouseButtons.Right Then
        Dim currSelectedColIdx = e.ColumnIndex
        ContextMenuStrip1.Show(Cursor.Position)
    End If
End Sub