How do I make the DataGridView show the selected row?

后端 未结 9 1225
傲寒
傲寒 2020-12-07 18:17

I need to force the DataGridView to show the selected row.

In short, I have a textbox that changes the DGV select

9条回答
  •  时光取名叫无心
    2020-12-07 19:04

    Doing something like this:

    dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];

    will only work if the first column is visible. If it is hidden, you'll get an exception. This is safer:

    var column = dataGridView1.CurrentCell != null ? dataGridView1.CurrentCell.ColumnIndex : dataGridView1.FirstDisplayedScrollingColumnIndex; dataGridView1.CurrentCell = dataGridView1.Rows[iNextHighlight].Cells[column];

    This will reset the selection without scrolling if the target row is already on screen. It also preserves the current column choice which can matter in cases where you've allowed inline editing.

提交回复
热议问题