3

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.

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257

3 Answers3

3
    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);
    }
gschuster
  • 98
  • 1
  • 8
1

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.

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
  • @shindigo - sorry, I was confused, I didn't notice that this wasn't your question in the first place :). – Alex Aza Jun 29 '11 at 18:04
0

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.

Chuck Savage
  • 11,775
  • 6
  • 49
  • 69