1
votes

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.

2
you click on the header column ?Abdellah OUMGHAR
Yes. It still gives me the index of the column that has a selected cell,DylanW80

2 Answers

1
votes

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.

0
votes

Your have probably probleme with declaration of your variable "currSelectedColIdx " :

Please try this code :

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