Selecting rows programmatically in DataGridView

manoj picture manoj · Jan 29, 2013 · Viewed 52.7k times · Source

I want to select row of previously selected rows after some event my code is as below.

int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;

after executing the code the preview will be as below. but i need to get the symbol > in id = 1272741 (blue selection) and not in 1272737

enter image description here

Answer

Alex Filipovici picture Alex Filipovici · Jan 29, 2013

Probably you might have taken a look at the DataGridView.CurrentRow Property, which is a read-only property:

Gets the row containing the current cell.

But in the remarks section, there is written:

To change the current row, you must set the CurrentCell property to a cell in the desired row.

Also, from the DataGridView.CurrentCell Property, we find out that:

When you change the value of this property, the SelectionChanged event occurs before the CurrentCellChanged event. Any SelectionChanged event handler accessing the CurrentCell property at this time will get its previous value.

So, there is no need that you actually select the currentRow becasue it will be selected when you set the CurrentCell value (unless you have some code to be executed inside the current scope between the SelectionChanged and CurrentCellChanged events). Try this:

//dgvIcbSubsInfo.Rows[currentRow].Selected = true;
dgvIcbSubsInfo.CurrentCell = dgvIcbSubsInfo.Rows[currentRow].Cells[0];