我有一个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中选择了新创建的项。但是,编辑控件坚持引用在创建新项之前选定的项。我如何鼓励他们指出新选定的项目?
发布于 2016-05-13 11:06:51
假设:
您正在向基础DataSource
中添加一个新行,而不是直接添加到DataGridView
。
结果:
您在这里遇到的问题是,所有编辑控件上的绑定都绑定到DataGridView.CurrentRow
绑定项--这是一个仅限get
的属性,由行标题列中的箭头指示。
改变CurrentRow
是在Selecting a row in a DataGridView and having the arrow on the row header follow中讨论的。
因此,它应该像将CurrentCell
设置为新添加的行的Cell[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];
https://stackoverflow.com/questions/37211331
复制