Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.net : How can I prompt a user if they are about to close their program with unsaved data?

I working working with Visual Basic 2010 Express. I have a DataGridView that is linked up with a local SQL database I've created. I have it currently where the user can click a button to save their data to the db, but am unsure how to prompt them to save or discard changes if they are closing the program without saving.

Thanks!

like image 213
daveomcd Avatar asked Dec 10 '22 12:12

daveomcd


2 Answers

Keep a global boolean (Dim _bDocumentChanged as boolean) and when any DataGridView events are fired set your boolean to True and then on the Form_Closing() check that boolean and throw a message box.

like image 155
Jim Avatar answered May 12 '23 05:05

Jim


I think you should also provide a cancel so the user can cancel the close without having to save the data or lose the changes they already made. Something like this:

    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
like image 44
Buck Hicks Avatar answered May 12 '23 03:05

Buck Hicks