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

时间:2016-05-13 13:29:20

标签: c# winforms data-binding datagridview bindingsource

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

HttpURLConnection

这在表面上很有效,在DataGridView中选择了新创建的项目。但是,编辑控件在引用创建新项目之前选择的项目时仍然存在。如何鼓励他们指向新选择的项目?

1 个答案:

答案 0 :(得分:1)

<强>假设:

您要向基础DataSource添加新行,而不是直接向DataGridView添加。

<强>结果:

您在这里遇到的问题是,所有编辑控件上的绑定都绑定到DataGridView.CurrentRow绑定项 - 这是get唯一属性,并由行中的箭头指示标题栏。

Selecting a row in a DataGridView and having the arrow on the row header follow中讨论了更改CurrentRow

所以它应该像设置新添加的行的CurrentCellCell[0]一样简单。除了...

CurrentCell事件中设置DataGridView.RowsAdded将失败。从概念上讲,它可以工作 - 新行变为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];