C# 更新后设置DataGridView SelectedRows

C# 更新后设置DataGridView SelectedRows,c#,winforms,datagridview,selecteditem,C#,Winforms,Datagridview,Selecteditem,在我的一个C Winform中,我有一个DataGridView,当用户按下刷新按钮时,我会更新它 问题是所选行在该过程中丢失 我希望能够做到以下几点: private void function Refresh() { UpdateBegin(); // Keep the selected row in memory Update(); UpdateEnd(); // Apply the selected row to the DataGridView } 这里是更新函数。它更新数据源,清除

在我的一个C Winform中,我有一个DataGridView,当用户按下刷新按钮时,我会更新它

问题是所选行在该过程中丢失

我希望能够做到以下几点:

private void function Refresh()
{
UpdateBegin(); // Keep the selected row in memory
Update();
UpdateEnd(); // Apply the selected row to the DataGridView
}
这里是更新函数。它更新数据源,清除所有列,并使用正确的标题文本返回所需的列:

private void Update()
{
    allItem = DataRepository.LotProvider.GetByIdProduit(detail.IdProduit)
dataGridView1.DataSource = allItem;
dataGridView1.Columns.Clear();
// Get a dictionary of the required column ID / shown text
Dictionary<string, string> dictionary = InitDisplayedFields();        
foreach (KeyValuePair<string, string> column in dictionary)
    // If the grid does not contain the key
    if (!dataGridView1.Columns.Contains(column.Key))
    {
        // Add the column (key-value)
        int id = dataGridView1.Columns.Add(column.Key, column.Value);
        // Bind the property
        dataGridView1.Columns[id].DataPropertyName = column.Key;
    }

}
但是,my DataGridView的selected rows属性是只读的


有解决方法吗?

您是否尝试过类似MSDN中有关此主题的以下摘录:

void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
    this.dataGridView1.Rows[e.RowIndex].Selected = true;
}
此代码段的第二行显示了如何以编程方式选择行,前提是您可以像在UpdateBegin函数调用中一样跟踪所选的RowIndex


希望这能有所帮助。

您能告诉我们更多关于更新的内容吗?它是否清除所有行,然后从某个数据库中提取最新的行?我问的原因是,您应该能够添加和删除行而不改变选择,除非您删除部分选择。在这种情况下,我相信选择只会被您删除的内容所改变。Update函数获取并更新数据源,清除dataGrid并返回所需的列。this.dataGridView1.Rows[e.RowIndex].Selected=true似乎是可行的方法。是的,它应该可以工作。还有另一个使用GridView.DataKeys的选项,但这一个可能就足够了。