How do I make a DataGridView immediately commit edits?

孤街浪徒 提交于 2019-11-28 11:39:47

Here's what was going on. The answer was in the properties of the ComboBox instances. I needed to change their DataSourceUpdateMode from OnValidation to OnPropertyChanged. This makes sense. The DataGridView was very likely showing the current state of the data. It was just that the data hadn't been edited yet because focus had not left the ComboBox, validating the input.

Thanks to everyone for your responses.

It looks like existing answers work well with BindingSource. In my case, where DataTable was directly used as a DataSource, they didn't work for some reason.

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

private Form1()
{
   var table = new DataTable();
   // ... fill the table ...
   dgv.DataSource = table;
}

After some hair-pulling, I got it work without adding BindingSource indirection:

// 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;
   // ...
}
Taher Rahgooy

Use this extension method. It works for all columns types, not just 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;
            };
        }

This method commits every change just after the change is made.

When we have a text column, after typing a character, its value will commit to the DataSource and the editmode of the cell will end.

Therefore current cell should return to edit mode, and position of the cursor set to end of text in order to enable user to continue typing reminder of the text.

this works well for me:

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

Call the DataGridView.EndEdit method.

Srishanth Kumar

following will work

_dataGrid.EndEdit()

s fine once you set the value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!