Right now if a user closes the form (either by clicking 'X' or chosing exit from a menu option) and changes are detected in the form, a messagebox will display asking the user if they would like to save any changes. The user has the option of clicking "yes, no or cancel." The problem I am having is with the cancel button. Every variation I've tried is still causing the form to close, even if cancelled is clicked. How can clicking cancel, essentially do nothing and go back to the form?

Private Sub PFC_XPRESS_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        Dim Result As DialogResult

If saved = False Then

                Result = MessageBox.Show("Would you like to save changes?", "Confirm Exit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

ElseIf Result = Windows.Forms.DialogResult.No Then
                Application.Exit()

Elseif Result = Windows.Forms.DialogResult.Cancel Then
                'Do Nothing

ElseIf Result = Windows.Forms.DialogResult.Yes Then

                Call Savefiledialog()

End If

Recommended Answers

All 3 Replies

Try this:

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'If there are unsaved changes to the active library, ask user what to do.

        Dim msgTitle As String = "You have unsaved changes"
        Dim msgPrompt As String = "Do you want to save your changes before closing?" & vbCrLf _
                                & vbCrLf _
                                & "    Yes    - save changes and exit" & vbCrLf _
                                & "    No     - discard changes and exit" & vbCrLf _
                                & "    Cancel - resume application"

        If Unsaved() Then

            Select Case MsgBox(msgPrompt, vbYesNoCancel, msgTitle)

                Case vbYes      'save changes and exit                                  
                    SaveBookList(Library)
                    MsgBox("Library has been saved in " & Library)

                Case vbCancel   'return to application                                  
                    e.Cancel = True

                Case vbNo       'discard changes and exit                               

            End Select

        End If

     End Sub

I used this in a BookLib app I wrote a while back. The Sub, Unsaved, returns true if there are changes that haven't been saved to disk.

It worked! Can't believe I forgot that part. Thanks Jim!

In case you missed it I revised the code a tad to give three options. It might have posted after you replied.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.