Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a DataGridView immediately commit edits?

I have a master-detail layout with a section of popup menus (the Details) and a section with a DataGridView which holds the rows.

The popup-menu state is updated when the selected row in the DataGridView changes and the state in the DGV's selected row should update when the popup-menu changes.

All of this works except the row in the DataGridView doesn't immediately update when I change the value of the popup-menu. I have to select a different row in order to see my edits.

I'm assuming this is because the edit hasn't been committed until the selection changes.

My question is: How do I make the change to the popup become immediately reflected in the DataGridView?

I have experimented with calling EndEdit() in the SelectionChangeCommitted handler for the popup-menu, but this has no effect. I'm interested in a technique that would allow me to create a DataGridView that would behave as if there were no Undo mechanism to begin with. Ideally the solution would be generic and transplantable to other projects.

like image 561
Michael Bishop Avatar asked Dec 07 '22 12:12

Michael Bishop


2 Answers

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;
   // ...
}
like image 97
snipsnipsnip Avatar answered Dec 09 '22 01:12

snipsnipsnip


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.

like image 32
Michael Bishop Avatar answered Dec 09 '22 01:12

Michael Bishop