|Task:||Save the current cell in a DataGridView even if the user hasn't moved off the cell in order to trigger the Dataset.HasChanges property|
If you have hooked a DataGridView up to a Dataset DataTable there is the possibility that a user could lose their edits if they make changes to a cell or add a new cell and immediately close the form without moving off the cell. The dataset's HasChanges property is only updated to True if the user edits a cell and moves off the cell. Use the FormClosing event to fire the DataGridView's EndEdit event which will commit the edits to the current cell. Then call the tableadapter's EndEdit event to cause the dataset's HasChanges property to change to True. You may now detect any edits and ask the user if they want to save them.
Private Sub frmUnits_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing TblUnitsDataGridView.EndEdit() 'Commit the current cell's edits, even if the user hasn't moved off the cell TblUnitsBindingSource.EndEdit() 'Commit the edits to the underlying data table and cause the dataset's HasChanges property to show True 'Ask the user if they want to save their edits If SheepMonitoringDataSet.HasChanges = True Then Dim SaveChanges As Integer = MsgBox("Save edits?", MsgBoxStyle.YesNoCancel, "Dataset has changes") Select Case SaveChanges Case 6 'yes, save the changes TblUnitsTableAdapter.Update(SheepMonitoringDataSet.tblUnits) SheepMonitoringDataSet.AcceptChanges() Case 2 'cancel form close event e.Cancel = True Case Else End Select End If End Sub