Tip: DataSet.HasChanges and Windows Form Close Button Strange Behavior
I had to write a simple Windows Forms application that haves a form. This form contains a DataGridView control that is binded with a DataSet; this DataSet is filled with data from an XML file. This Windows Forms contains two buttons: "Accept Changes" and "Cancel Changes".
The "Accept Changes" and "Cancel Changes" buttons works greatly, the first one writes the content of the DataGridView control in a XML DataSet, and the second one simply cancel the data insertion, delete or modifying operation and shows a message indicating to the user if wants to discard or save all changes made to the DataGridView control. Both the "Cancel Changes" and the standard window close button executes the following method:
1: private void CloseWindow()
2: {3: dvProviders = dgvProviders.DataSource as DataView;
4: DataSet dsProviders = dvProviders.Table.DataSet;
5:
6: if (dsProviders.HasChanges())
7: {8: DialogResult saveChanges = MessageBox.Show("¿Save Changes?",9: "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
10:
11: if saveChanges == DialogResult.Yes)
12: {13: //Save the changes from the DataSet to an XML file
14: this.SaveChanges();
15: }
16: }
17: }
But what happens if the user close the window using the standard window's close button and the DataGridView's DataSource (a DataSet) have pending changes?
It is expected that the button execute the CloseWindow method and detect if the DataSet has changes, but in a rare way when the code ask for the result of the DataSet's HasChanges method, it returns a false value and all the changes made in the DataGridView control are lost when the window close.
Well, Fortunately with the help of a coworker that told me that it was a "Bug" or better called "Windows Form's rare behavior". He told me that I need to move the focus of the DataGridView control to other control in the form (for example the Accept Changes button) before asking for the DataSet's HasChanges method, this way the DataGridView control apply the changes to the DataSet and the HasChanges return true (if any change is made to the DataGridView control) and the method's execution continues normally.
5: // Set the focus to other control
6: btnAcceptChanges.Focus();
8: if (dsProviders.HasChanges())
Thanks to Alberto Puyana for help me find the answer to this windows close button strange behavior.