C# 在DataGridView中以编程方式选择行

C# 在DataGridView中以编程方式选择行,c#,.net,visual-studio-2010,datagridview,C#,.net,Visual Studio 2010,Datagridview,我想在某个事件后选择以前选择的行,我的代码如下 int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex; //code to execute dgvIcbSubsInfo.Rows[currentRow].Selected = true; 执行代码后,预览如下所示。但是我需要在id=1272741(蓝色选择)中获得符号,而不是在1272737中 我想您希望突出显示这一行。请尝试以下代码,我认为可能会有所帮助: Color color = dgv

我想在某个事件后选择以前选择的行,我的代码如下

int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;
执行代码后,预览如下所示。但是我需要在id=1272741(蓝色选择)中获得符号
,而不是在1272737中


我想您希望突出显示这一行。请尝试以下代码,我认为可能会有所帮助:

Color color = dgv.Rows[prevRowIndex].DefaultCellStyle.SelectionBackColor;
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = color;

您可能已经查看了,这是一个只读属性:

获取包含当前单元格的行

但在备注部分,有以下内容:

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

此外,从中,我们发现:

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

因此,无需实际选择
currentRow
,因为在设置
CurrentCell
值时会选择它(除非在
SelectionChanged
CurrentCellChanged
事件之间的当前范围内有一些代码要执行)。试试这个:

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

请尝试以下操作以更改当前行。因为OP有点不清楚哪一行应该是新行,所以我的示例只是显示了从当前行移动到前一行(如果有前一行)。第一行代码是可选的。如果不想使用FullRowSelect,还可以将列硬编码为0(或某些其他列)以使用固定列

dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
int row = dataGridView.CurrentCell.RowIndex;
int firstRow = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.None);
if (row != firstRow)
{
  row--;
  int col = dataGridView.CurrentCell.ColumnIndex;
  dataGridView.CurrentCell = dataGridView[col, row];
}

伙计,这个问题很难理解,不够清楚!>表示第一行的选择箭头问题是所选项目的行索引发生了更改(例如,在对数据源进行排序或重新查询后)。这是对代码和注释的深入了解,也是对如何获得答案的全面解释。谢谢你,亚历克斯!