如何让 DataGridView 立即提交编辑?

问题描述 投票:0回答:6

我有一个主从布局,其中包含弹出菜单部分(详细信息)和包含行的 DataGridView 部分。

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

所有这些都有效,除了当我更改弹出菜单的值时,DataGridView 中的行不会立即更新。我必须选择不同的行才能看到我的编辑。

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

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

我尝试在弹出菜单的 SelectionChangeCommited 处理程序中调用 EndEdit(),但这没有效果。我对一种技术感兴趣,该技术允许我创建一个 DataGridView,其行为就像一开始就没有撤消机制一样。理想情况下,该解决方案应该是通用的并且可以移植到其他项目。

c# datagridview master-detail undo
6个回答
7
投票

看起来现有答案与

BindingSource
配合得很好。就我而言,直接使用
DataTable
作为
DataSource
,由于某种原因它们不起作用。

// Other answers didn't work in my setup...
private DataGridView dgv;

private Form1()
{
   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();
}

private Form1()
{
   dgv.CellEndEdit += dgv_CellEndEdit;
   // ...
}

4
投票

事情是这样的。答案就在

ComboBox
实例的属性中。我需要将他们的
DataSourceUpdateMode
OnValidation
更改为
OnPropertyChanged
。这是有道理的。
DataGridView
很可能显示数据的当前状态。只是数据还没有被编辑,因为焦点还没有离开
ComboBox
,验证输入。

感谢大家的回复。


4
投票

这对我来说效果很好:

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

2
投票

使用这个扩展方法。它适用于所有列类型,而不仅仅是组合框:

        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;
            };
        }

此方法在更改完成后立即提交所有更改。

当我们有一个文本列时,输入一个字符后,其值将提交到数据源,并且单元格的编辑模式将结束。

因此当前单元格应返回编辑模式,并将光标位置设置为文本末尾,以便用户继续输入文本提示。


0
投票

调用 DataGridView.EndEdit 方法。


-1
投票

以下将起作用

_dataGrid.EndEdit()

设置好值后就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.