在DataGridView中以编程方式选择行 [英] Selecting rows programmatically in DataGridView
问题描述
我想在某些事件之后选择先前选择的行,我的代码如下所示。
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;
执行代码后,预览如下。但是我需要在id = 1272741(蓝色选择)中获得符号>
而不是1272737
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
< img src =https://i.stack.imgur.com/4tipE.pngalt =enter image description here>
推荐答案
可能您可能已经看过 DataGridView.CurrentRow属性,这是一个只读属性:
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:
更改当前行,您必须设置
CurrentCell
属性到所需行中的
单元格。
To change the current row, you must set the
CurrentCell
property to a cell in the desired row.
另外,从 DataGridView.CurrentCell属性,我们发现:
当您更改该属性的值,SelectionChanged事件
出现在CurrentCellChanged事件之前。任何SelectionChanged事件
处理程序此时访问CurrentCell属性将获得其
以前的值。
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.
所以,您不需要实际选择 currentRow
,因为您设置 CurrentCell
值时将被选中(除非您在 SelectionChanged
与 CurrentCellChanged
事件之间的当前范围内执行一些代码。尝试这样:
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];
这篇关于在DataGridView中以编程方式选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!