How can I use the right-click context menu in a DataGridView?

I created a context menu and attached to the DataGridView control. However, I noticed that when I right-click on a control, the selection in the dataGridView does not change. Therefore, I cannot get the string correctly in the context event handler.

Any suggestions on how I can do this?

Imagine that I have an identifier, and when I click the delete context menu, I want to delete this particular record from the database.

I just need information on how to get this id , I can deal with deleting myself.

+3
source share
3 answers

Add

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

currentRow .

0
    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);
    }
+3

, .

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 the Click event handler from your menu item, check the GridView1.CurrentRow data to find out which row is currently selected. For example, if the grid is bound to a data source:

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

When testing this code, make sure that the DataGridView.ContextMenuStrip property is not set.

+1
source

All Articles