Saving Changes to a DataTable bound to a DataGridView
Ok,
So I'm working on app that binds a datatable to a data grid view. Normally you would just edit right in the grid and be done. However our table has too much data to edit right in the grid so instead users have to click a row on the grid to load a details panel below the grid. This works great except I noticed changes made to the last row weren't being saved. This is because the grids don't commit changes to their datasource unless a new row is clicked. So after a few hours of digging I found this bit of code worked very well.
Check that the object in this case a data table being used to bind exists. And if it does call the end current edit on that object. However if you're binding to a custom collection of objects I believe you need to implement a certain interface for this to work.
Quick update!
I found for custom collections etc, you need to implement the IEditableObject interface. Also when calling the EndCurrentEdit this ends all databinding on the grid so you need to re-bind the datasource to the grid.
So I'm working on app that binds a datatable to a data grid view. Normally you would just edit right in the grid and be done. However our table has too much data to edit right in the grid so instead users have to click a row on the grid to load a details panel below the grid. This works great except I noticed changes made to the last row weren't being saved. This is because the grids don't commit changes to their datasource unless a new row is clicked. So after a few hours of digging I found this bit of code worked very well.
// commit all our changes to the datasource of our grid
if( dataGridViewVariables.BindingContext[_tableEditVariables] != null )
{
dataGridViewVariables.BindingContext[_tableEditVariables].EndCurrentEdit();
}//end if
Check that the object in this case a data table being used to bind exists. And if it does call the end current edit on that object. However if you're binding to a custom collection of objects I believe you need to implement a certain interface for this to work.
Quick update!
I found for custom collections etc, you need to implement the IEditableObject interface. Also when calling the EndCurrentEdit this ends all databinding on the grid so you need to re-bind the datasource to the grid.
Comments
Cheers!
Thanks
Wokrs great! :)
I just needed to Google how to use binding context.
I basically had a Grid_View that has its Data Source set to a Data_Table.
Everytime I update the Grid_View I needed to create a new row so my changes are added to the Data_Table. But using
Me.BindingContext(Data_Table).EndCurrentEdit()
after a cell_value_Changed event made it work perfectly.
Cheers.