DylanW80 DylanW80 - 2 years ago 178
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
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download