user278618
user278618

Reputation: 20222

Get RowIndex via ContextMenu?

I'm trying to get a rowindex of row at which I right clicked to call a contextmenu.

DatagridView's property contextmenu is set to this contextmenu.

Is it possible in some simple way?

Best regards

Upvotes: 2

Views: 1668

Answers (2)

noelicus
noelicus

Reputation: 15055

I change the selection in the CellContextMenuStripNeeded event and then use the SelectedRows member to find it.

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

This also has the desired effect of highlighting a row that you r-click on.

Upvotes: 0

Ben Hoffstein
Ben Hoffstein

Reputation: 103325

Yes, you need to handle the MouseDown event for your DataGridView and then use the HitTest method to return row and/or column index for the given coordinates.

For example:

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

Upvotes: 1

Related Questions