Winforms 通过ContextMenu获取行索引?

Winforms 通过ContextMenu获取行索引?,winforms,datagridview,Winforms,Datagridview,我正在尝试获取我右键单击以调用contextmenu的行的行索引 DatagridView的属性contextmenu设置为此contextmenu 有没有可能用简单的方法 致意是的,您需要为DataGridView处理MouseDown事件,然后使用HitTest方法返回给定坐标的行和/或列索引 例如: private void dataGridView1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == Mous

我正在尝试获取我右键单击以调用contextmenu的行的行索引

DatagridView的属性contextmenu设置为此contextmenu

有没有可能用简单的方法


致意

是的,您需要为DataGridView处理MouseDown事件,然后使用HitTest方法返回给定坐标的行和/或列索引

例如:

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)
        {
            Console.WriteLine(hit.RowIndex);
        }
    }
}

我在
CellContextMenuStripNeeded
事件中更改选择,然后使用
SelectedRows
成员查找它

private void dataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    var Dgv = sender as DataGridView;
    if (Dgv != null)
    {
        // Change the selection to reflect the right-click
        Dgv.ClearSelection();
        Dgv.Rows[e.RowIndex].Selected = true;
    }
}

private void myToolStripMenuItem_Click(object sender, EventArgs e)
{
    // Now pick up the selection as we know this is the row we right-clicked on
    if (dataGridView.SelectedRows.Count > 0)
    {
        DoSomethingAmazing(dataGridView.SelectedRows[0]);
    }
}
这还具有所需的效果,即高亮显示右键单击的行