如何让DataGridView立即提交编辑?

我有一个主 – 细节布局,其中包含一段弹出菜单(详细信息)和一个包含DataGridView的部分,用于保存行。

当DataGridView中的选定行发生更改时,弹出菜单状态会更新,并且当弹出菜单更改时,DGV所选行中的状态应更新。

当我更改弹出菜单的值时, 除了 DataGridView中的行之外 ,所有这些都有效。 我必须选择一个不同的行才能看到我的编辑内容。

我假设这是因为在选择更改之前尚未提交编辑。

我的问题是:如何让弹出窗口的更改立即反映在DataGridView中?

我已尝试在弹出菜单的SelectionChangeCommitted处理程序中调用EndEdit(),但这没有任何效果。 我对一种技术很感兴趣,这种技术可以让我创建一个DataGridView,就像没有Undo机制一样。 理想情况下,解决方案是通用的,可移植到其他项目。

这是发生了什么。 答案是在ComboBox实例的属性中。 我需要将他们的DataSourceUpdateModeOnValidation更改为OnPropertyChanged 。 这是有道理的。 DataGridView很可能显示数据的当前状态。 只是数据尚未编辑,因为焦点没有离开ComboBox ,validation输入。

感谢大家的回复。

看起来现有的答案适用于BindingSource 。 在我的情况下, DataTable直接用作DataSource ,但由于某些原因它们不起作用。

 // Other answers didn't work in my setup private DataGridView dgv; private Form1() { dgv.CellEndEdit += dgv_CellEndEdit; var table = new DataTable(); // ... fill the table ... dgv.DataSource = table; } 

经过一些拉毛后,我得到了它,但没有添加BindingSource间接:

 // Add this event handler to the DataGridView private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e) { dgv.BindingContext[dgv.DataSource].EndCurrentEdit(); } 

使用此扩展方法。 它适用于所有列类型,而不仅仅是ComboBoxes:

  public static void ChangeEditModeToOnPropertyChanged(this DataGridView gv) { gv.CurrentCellDirtyStateChanged += (sender, args) => { gv.CommitEdit(DataGridViewDataErrorContexts.Commit); if (gv.CurrentCell == null) return; if (gv.CurrentCell.EditType != typeof(DataGridViewTextBoxEditingControl)) return; gv.BeginEdit(false); var textBox = (TextBox)gv.EditingControl; textBox.SelectionStart = textBox.Text.Length; }; } 

此方法在更改后立即提交每个更改。

当我们有一个文本列时,在键入一个字符后,它的值将提交给DataSource,并且该单元格的editmode将结束。

因此,当前单元格应返回编辑模式,并将光标位置设置为文本结尾,以使用户能够继续键入文本提醒。

调用DataGridView.EndEdit方法。

这适合我:

 private void CurrentCellDirtyStateChanged(object sender, EventArgs e) { var dgw = (DataGridView) sender; dgw.CommitEdit(DataGridViewDataErrorContexts.Commit); } 

以下将有效

 _dataGrid.EndEdit() 

一旦设置了值,就可以了。