Only Bolivian Here
Only Bolivian Here

Reputation: 36733

How can I use a right click context menu on a DataGridView?

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.

Upvotes: 3

Views: 9394

Answers (3)

gschuster
gschuster

Reputation: 98

    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);
    }

Upvotes: 3

Alex Aza
Alex Aza

Reputation: 78447

This is how you could show context menu and select current cell if a cell is clicked.

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
        if (hit.Type == DataGridViewHitTestType.Cell)
        {
            dataGridView1.CurrentCell = dataGridView1[hit.ColumnIndex, hit.RowIndex];
            contextMenuStrip1.Show(dataGridView1, e.X, e.Y);
        }
    }
}

In Click event handler from your menu item check dataGridView1.CurrentRow to find out which row is currently selected. For example, if the grid is bound to a datasource:

private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    var item = dataGridView1.CurrentRow.DataBoundItem;
}

When you test this code, make sure that DataGridView.ContextMenuStrip property is not set.

Upvotes: 1

Chuck Savage
Chuck Savage

Reputation: 11945

Add,

DataGridViewRow currentRow;
void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex >= 0)
        currentRow = self.Rows[e.RowIndex];
    else
        currentRow = null;
}

Then use currentRow in your context menu method.

Upvotes: 0

Related Questions