DataGridView 新项目的编程选择不会更新其他数据绑定控件

DataGridView programatic selection of new item does not update other data-bound controls

我有一个 DataGridView 和许多控件(用于编辑)都绑定到一个 BindingSource。一切都按预期工作 - 单击 DataGridView 中的条目会导致绑定的编辑控件显示和编辑所选项目。我想要做的是在 DataGridView 中自动选择新创建的项目,编辑控件也绑定到新创建的数据。为此,我为 DataGridView.RowsAdded 实现了一个处理程序,如下所示:

private void dataGridViewBeasts_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    // Force newly created items to be selected
    dataGridViewBeasts.Rows[e.RowIndex].Selected = true;
}

这在表面上有效,在 DataGridView 中选择了新创建的项目。但是,编辑控件坚持引用在创建新项目之前选择的项目。我怎样才能鼓励他们指向新选择的项目?

假设:

您正在将新行添加到基础 DataSource,而不是直接添加到 DataGridView

结果:

您在这里遇到的问题是所有编辑控件上的绑定都绑定到 DataGridView.CurrentRow 绑定项目 - 这是一个 get 仅 属性 并且被指示通过行 header 列中的箭头。

更改 CurrentRowSelecting a row in a DataGridView and having the arrow on the row header follow 中讨论。

所以应该很简单,只要将新增行的CurrentCell设置为Cell[0]即可。除了...

DataGridView.RowsAdded 事件中设置 CurrentCell 将失败。从概念上讲,它是有效的——新行变成 CurrentRow。但在该事件完成后,调试将显示 CurrentRow 立即重置为其先前的值。相反,在您的代码之后设置 CurrentCell 以添加新行。例如当 BindingSource.DataSource:

是一个DataTable:

DataTable dt = theBindingSource.DataSource as DataTable;
dt.Rows.Add("New Row", "9000");

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];

或者List<Example>:

List<Example> list = theBindingSource.DataSource as List<Example>;
list.Add(new Example() { Foo = "New Row", Bar = "9000" });

// Reset the bindings.
dataGridView1.DataSource = null;
dataGridView1.DataSource = theBindingSource;

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];