Skip to main content
 首页 » 编程设计

C# 如何以编程方式重新定位 DataGridView 上的行选择

2024年02月23日14cloudgamer

我正在使用 linq2sql 将记录添加到我的数据 GridView 并刷新网格。刷新后立即将行选择移动到顶部。我如何告诉它突出显示最近添加的记录?

不确定这是否有帮助,但我在下面包含了我用来找出所选行的 pk 的代码。因为我想做的是相反的。谢谢

        //get selected row index 
        int index = this.dataGridView1.CurrentRow.Index; 
        //get pk of selected row using index 
        string cellValue = dataGridView1["pkColumn", index].Value.ToString(); 
        //change pk string to int 
        int pKey = Int32.Parse(cellValue); 

请您参考如下方法:

如果您事先知道无论何时添加新项目,它都应该出现在列表底部,您可以使用:

    int index = this.dataGridView1.Rows.Count - 1; 
    this.dataGridView1.Rows[index].Selected = true; 
    this.dataGridView1.FirstDisplayedScrollingRowIndex = index; 

但是,如果您按其他列对列表进行排序,那么您将不会获得所需的结果。

我建议你,是搜索你需要选择的行索引,这可以通过一个函数来执行,比方说 int SearchRowIndexForPKValue(int pKey),它将执行在包含您的 PK/ID ("pkColumn") 的列的单元格值中查找返回行索引。这样上面的代码应该是这样的:

    int index =  SearchRowIndexForPKValue(pKey); 
    this.dataGridView1.Rows[index].Selected = true; 
    this.dataGridView1.FirstDisplayedScrollingRowIndex = index; 

编辑:int SearchRowIndexForPKValue(int pKey) 不是DataGridView 的现有内置方法。您必须声明它并在您的代码中实现它;对于方法的主体,您可以从 this post 中获取代码.