【问题标题】:Set DataGridView SelectedRows after Update更新后设置 DataGridView SelectedRows
【发布时间】:2013-05-07 18:19:45
【问题描述】:

在我的一个 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;
    }

}

但是,我的 DataGridView 的 selected rows 属性是只读的。

有解决办法吗?

【问题讨论】:

  • 您能告诉我们更多关于您的更新的功能吗?它会清除所有行,然后从某个数据库中提取最新的吗?我问的原因是,您应该能够在不更改选择的情况下添加和删除行,除非您删除部分选择。在这种情况下,我相信选择只会因您删除的内容而改变。
  • Update 函数获取并更新数据源,清除 dataGrid 并带回所需的列。

标签: c# winforms datagridview selecteditem


【解决方案1】:

您是否尝试过类似 MSDN (link) 关于此主题的以下摘录:

void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
    this.dataGridView1.Rows[e.RowIndex].Selected = true;
}

此代码中的第二行 sn-p 显示了如何以编程方式选择行,前提是您跟踪选定的 RowIndex(可能在您的 UpdateBegin() 函数调用中完成)。

希望这会有所帮助。

【讨论】:

  • this.dataGridView1.Rows[e.RowIndex].Selected = true 似乎是要走的路。
  • 是的,它应该可以工作。还有另一种使用 GridView.DataKeys 的选项,但这个可能就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多