VB.net: how can I invite a user if they are going to close their program with unsaved data?

I am working with Visual Basic 2010 Express. I have a DataGridView that is connected to a local SQL database that I created. I have it now, when the user can click the button to save their data in db, but I don’t know how to make them save or cancel the changes if they close the program without saving.

Thanks!

+4
source share
5 answers

Keep the global boolean value ( Dim _bDocumentChanged as boolean ), and when any DataGridView events are fired, set boolean to True and then on the Form_Closing () check, which will be logical and will display a message box.

+6
source

I think you should also cancel the cancellation so that the user can cancel the closure without having to save the data or lose the changes already made. Something like that:

  Private Sub frmMain_FormClosing(ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing Dim Answer As DialogResult = MessageBox.Show("Save Data before close?", _ "Data Check", MessageBoxButtons.YesNoCancel) Select Case Answer Case Windows.Forms.DialogResult.Yes SaveRecords() Case Windows.Forms.DialogResult.No Exit Sub Case Windows.Forms.DialogResult.Cancel e.Cancel = True Case Else Exit Sub End Select End Sub 
+4
source

I would ask them to use your Form OnClosing event. Something like this should do the trick:

 Private Sub YourDataGridViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing If MessageBox.Show(Me, "Do you want to save your changes?", "Unsaved Changes!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then SaveChanges() End If End Sub Private Sub SaveChanges() MessageBox.Show("Changes saved...") End Sub 
+2
source

Trap closing application. The first thing you do is request the user. if they say yes, then save. Then perform a normal shutdown.

You can also save a flag to track the presence of any unsaved data. This is cleared when the user saves, but sets when they make changes.

+1
source

I would suggest a trap with the FormClosing event in the main window. Remember, when the main window closes, the application terminates. If this is an MDI application, you must verify that each child window is properly saved before allowing the application to terminate.

+1
source

All Articles