DylanW80 DylanW80 - 6 months ago 40
Vb.net Question

VB.NET - Datagridview: Get index of clicked column

In VB.NET's DataGridView, how can i get the index of the column that was clicked on, instead of the one that that has a selected cell.

I wish to provide the user with the option to right click the column and hide it, via a context menu. This code gives me the index of the column that has a selected cell:

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


Edit: The problem happens when i bind the contextmenu to the datagridview via the properties window. If i unbind it, the code works correctly.

Answer

You can use CellContextMenuStripNeeded event of DataGridView.

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

you can get index of column with : e.ColumnIndex.

Comments