Context menu for datagridview, rowheader and headheader cells

I want to set another context menu for datagridview cells, row headers and columns. The idea is that when you right-click on any of these items, another context menu is displayed. How to do it?

+8
source share
2 answers

Use the DataGridView MouseDown event to check whether the right mouse button has been clicked, and if so, use the associated HitTestInfo property to determine whether a cell, row, or column has been clicked. Use this information to display the ContextMenuStrip that you need.

Here is an example of MouseDown that does this. To try a sample, clear the DataGridView and the three ContentMenuStrips in the form. Name ContentMenuStrips mnuCell, mnuRow, and mnuColumn.

 Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown If e.Button = Windows.Forms.MouseButtons.Right Then Dim ht As DataGridView.HitTestInfo ht = Me.DataGridView1.HitTest(eX, eY) If ht.Type = DataGridViewHitTestType.Cell Then DataGridView1.ContextMenuStrip = mnuCell mnuCell.Items(0).Text = String.Format("This is the cell at {0}, {1}", ht.ColumnIndex, ht.RowIndex) ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then DataGridView1.ContextMenuStrip = mnuRow mnuRow.Items(0).Text = "This is row " + ht.RowIndex.ToString() ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then DataGridView1.ContextMenuStrip = mnuColumn mnuColumn.Items(0).Text = "This is col " + ht.ColumnIndex.ToString() End If End If End Sub 

Here I assign the DataGridView property ContextMenuStrip to ContextMenuStrip, suitable for the right-clicked item (cell, row or column). To demonstrate how you can customize the behavior of ContextMenuStrips, I also customize the text in each ContentMenuStrips menu item.

+19
source

In the MouseDown event of the DataGridView, use the DataGridView.HitTest method to verify what was clicked. Then you can switch context menus depending on what was clicked.

+2
source

All Articles