C# – How to use a right click context menu on a DataGridView

cdatagridviewwinforms

I've created a context menu, and associated to my DataGridView control. However, I noticed that when I right click on the control, the selection in the dataGridView isn't changed. So I can't correctly fetch the row in the context's event handler.

Any suggestions on how I could accomplish this?

Imagine I have an ID olumn, and when I click the delete context menu, I want to delete that particular entry from the database.

I just need the information on how to get that id, I can handle the deleting myself.

Best Answer

    private void dataGridViewSource_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button != MouseButtons.Right || e.RowIndex == -1 || e.ColumnIndex == -1) return;
        dataGridViewSource.CurrentCell = dataGridViewSource.Rows[e.RowIndex].Cells[e.ColumnIndex];
        contextMenuStripGrid.Show(Cursor.Position);
    }