在DataGridView中以编程方式选择行

man*_*noj 22 .net c# datagridview visual-studio-2010

我希望在某些事件之后选择之前选定行的行,我的代码如下所示.

int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;
Run Code Online (Sandbox Code Playgroud)

执行代码后,预览将如下所示.但我需要>在id = 1272741(蓝色选择)中获取符号,而不是在1272737中

在此输入图像描述

Ale*_*ici 48

可能你可能已经看过DataGridView.CurrentRow属性,它是一个只读属性:

获取包含当前单元格的行.

但在备注部分,有写道:

要更改当前行,必须将该CurrentCell属性设置为所需行中的单元格.

另外,从DataGridView.CurrentCell属性中,我们发现:

更改此属性的值时,SelectionChanged事件发生在CurrentCellChanged事件之前.此时访问CurrentCell属性的任何SelectionChanged事件处理程序都将获得其先前的值.

因此,您不需要实际选择,currentRow因为在设置CurrentCell值时将选择它(除非您在SelectionChangedCurrentCellChanged事件之间的当前范围内执行某些代码).试试这个:

//dgvIcbSubsInfo.Rows[currentRow].Selected = true;
dgvIcbSubsInfo.CurrentCell = dgvIcbSubsInfo.Rows[currentRow].Cells[0];
Run Code Online (Sandbox Code Playgroud)