Answered Context menu in DataGridView

cbreemer

Well-known member
Joined
Dec 1, 2021
Messages
188
Programming Experience
10+
I am implementing a contextmenu on my DataGridview. It works well but I want to make it more dynamic, so that certain items are disabled depending on the row that was right mouse clicked on, and that the menu does not appear when I click on the header row. I figured that the ContextMenuStrip's Opening event was the place to do that stuff, but I can't seem to find out which row was clicked on. I can get a reference to the menu (the sender object) and to the grid (the SourceControl property) but neither has the information I need. I have a feeling I am missing something here... Perhaps I need a different or additional event ?
The same question raises again when I am in the click events of the menu items.
 
Last edited:
Last edited:
Solution
There's an example here that capture the row/column with CellMouseEnter event: DataGridViewRow.ContextMenuStrip Property (System.Windows.Forms)

Perhaps this is also useful: DataGridView.CellContextMenuStripNeeded Event (System.Windows.Forms)
That example works, thanks !!
I had tried something similar, but I picked the CellMouseClick event, only to find out that isn't fired anymore once the grid has a ContextMenuStrip.
The CellContextMenuStripNeeded event is also an option but seems a bit overkill for my purpose. I prefer the simple and clear hack :)
 
Assuming that you have assigned contextMenuStrip1 to the ContextMenuStrip property of dataGridView1, this code will open the menu if and only if you right-click on a data cell in the grid:
C#:
private DataGridViewRow rightClickedRow = null;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Right)
    {
        return;
    }

    var test = dataGridView1.HitTest(e.X, e.Y);

    rightClickedRow = null;

    if (test.Type == DataGridViewHitTestType.Cell)
    {
        rightClickedRow = dataGridView1.Rows[test.RowIndex];
    }
}

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
    e.Cancel = rightClickedRow == null;
}
You can then refer to rightClickedRow in the Click event handlers of your menu items.
 

Latest posts

Back
Top Bottom