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.

// 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

Anonymous said…
I've just spent several hours trying to work this out - your solution seems to work better than any other I've seen.

Cheers!
Anonymous said…
Solution is great, thanks!
Anonymous said…
That was GREAT!
Thanks
Anonymous said…
Thanks for this short solution. I couldn't really understand how should I suddenly use BindingContext when I bind to DataTable and this kind of helped.

Wokrs great! :)
Dan said…
Thanks for posting this solution. This has been an issue I have been struggling with forever.
Tony Awad said…
This comment has been removed by the author.
Tony Awad said…
This works perfectly fine.
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.

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC