在DataGridView中编程选择行

25
我希望能在某些事件后选择之前已选行的行。我的代码如下。
int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;

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

图片描述


兄弟,这个问题难以理解,不够清晰明了! - wcraft
1
表示首行选择箭头
- manoj
问题在于所选项目的行索引已更改(例如,在排序或重新查询数据源后)。 - Olivier Jacot-Descombes
4个回答

56

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

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

但在备注中写道:

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

此外,从DataGridView.CurrentCell属性中得知:

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

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

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

1
这真是一次非常好的代码和注释挖掘,以及对你如何得出答案的全面解释。谢谢Alex! - Jody Sowald

0
尝试以下方法来更改当前行。由于原帖不太清楚新行应该是哪一行,我的示例仅显示从当前行移动到上一行(如果有上一行)。第一行代码是可选的。如果您不想使用FullRowSelect,也可以将col硬编码为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];
}

0
我来这里是想学习如何以编程方式选择DataGridView控件中的行。以下是选择名为dg1的DataGridView控件中顶部行并"点击"它的方法:
dg1.Rows[0].Selected = true;                      

dg1_RowHeaderMouseClick(null, null);

接下来调用以下事件,该事件期望选择一行。

private void dg1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {                        
        var selectedRows = dg1.SelectedRows;

        // Make sure we have a single row selected
        int count = selectedRows.Count;

        if (count == 1)
        {                
            tbAssemblyName.Text = dg1.SelectedRows[0].Cells[0].Value.ToString();                
        }
    }

当用户单击他们想要的行时,我已经使一切正常。当只有一条记录可供选择时,我希望为用户“点击”它。


0

我觉得你想要突出显示这一行。请尝试以下代码,我认为它可能会有所帮助:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接