如何在DataGridView上使用右键菜单?

3
我已经创建了一个上下文菜单,并将其与我的DataGridView控件关联。然而,我注意到当我右键单击控件时,dataGridView中的选择并没有改变。因此,在上下文事件处理程序中,我无法正确获取行。
你有什么建议吗?如果我有一个ID列,当我点击删除上下文菜单时,我想从数据库中删除该特定条目。
我只需要有关如何获取该id的信息,我可以自己处理删除。
3个回答

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

1

如果单击单元格,您可以这样显示上下文菜单并选择当前单元格。

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

在菜单项的 Click 事件处理程序中,检查 dataGridView1.CurrentRow 以找出当前选择了哪一行。例如,如果网格绑定到数据源:
private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    var item = dataGridView1.CurrentRow.DataBoundItem;
}

当你测试这段代码时,请确保未设置 DataGridView.ContextMenuStrip 属性。


@shindigo - 抱歉,我有点困惑,一开始没有注意到这不是你的问题 :)。 - Alex Aza

0

添加,

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

然后在您的上下文菜单方法中使用currentRow。


如果你在网格上添加 CellMouseDown 处理程序,它就会执行。 - Chuck Savage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接