Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place DataGridView''s row indicator for manually selected row

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?

falsely placed row indicator

like image 508
Jörg Battermann Avatar asked Jul 25 '11 15:07

Jörg Battermann


People also ask

How to select a specific row in DataGridView?

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.

How do I get the index of a selected row?

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.

How do I pass DataGridView selected row value to textbox in another form?

Text = Convert. ToString(frm. DataGridView1[1, row]. Value);


1 Answers

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];
}
like image 193
David Hall Avatar answered Oct 13 '22 22:10

David Hall