Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 183
  • Last Modified:

How do I prevent a form from closing when the close button (X) is selected?

Hi,
I want to be able to prevent an application from closing if the user did not save their data correctly. e.g. they missed completing a field properly.  I am using the  form_Closing sub but when I call exit sub the application still terminates.  How can I prevent this?

Private Sub myform_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If mbSaveNeeded Then
            If MsgBox("Save changes to current record?", MsgBoxStyle.Question.YesNo) = MsgBoxResult.Yes Then
                If Not DBSaveEntries() Then
                    Exit Sub THIS DOES NOT HELP BECAUSE THE FORM EXITS ANYWAYS
                End If
            End If
        End If
        mWB = Nothing
        End
    End Sub
0
fowlow
Asked:
fowlow
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
To prevent closure of the form, set the Cancel property of the e variable passed into the Closing event to True like this:

    Private Sub myform_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If mbSaveNeeded Then
            If MsgBox("Save changes to current record?", MsgBoxStyle.Question.YesNo) = MsgBoxResult.Yes Then
                If Not DBSaveEntries() Then
                    e.Cancel = True ' <--------  This causes the Closing event to be cancelled                    
                End If
            End If
        End If
        mWB = Nothing
        End
    End Sub
0
 
fowlowAuthor Commented:
Exactly the answer I needed.
Thank-you very much.
Tim
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now