I have the following code in a WinForms datagridview for handling right-mouse-clicks to select the underlying row:
private void dataGridViewTestSteps_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right) return;
var hitTestInfo = dataGridViewTestSteps.HitTest(e.X, e.Y);
dataGridViewTestSteps.ClearSelection();
dataGridViewTestSteps.Rows[hitTestInfo.RowIndex].Selected = true;
}
... now this works fine, but it does not place the small indicator in the correct row (see image below). So basically I was wondering what's missing in the method above?
To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.
Solution: You can get the selected row indexes by using the selectedRowsIndexes property in Grid. The following code example shows how to get the selected row indexes in Grid.
Text = Convert. ToString(frm. DataGridView1[1, row]. Value);
The row header cursor shows the current row, not the selected row - they are actually different, since you can have multiple selected rows but only one current row.
Try this code instead:
private void dataGridViewTestSteps_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right) return;
var hitTestInfo = dataGridViewTestSteps.HitTest(e.X, e.Y);
//dataGridViewTestSteps.ClearSelection();
//dataGridViewTestSteps.Rows[hitTestInfo.RowIndex].Selected = true;
dataGridViewTestSteps.CurrentCell = dataGridViewTestSteps.Rows[hitTestInfo.RowIndex].Cells[0];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With