Cancel button not responding to Form1 closing

DiverDan

Contributor
Joined
Jan 16, 2003
Messages
645
Location
Sacramento, CA
Hi, I'm calling a checkSave sub prior to the closing of Form1. The checkSave sub creates a yes, no, cancel message box and from the button selection sets a boolean value on varaible continue.

Code is:
Visual Basic:
    Sub checkSave()
        If worksheetModified = True Then
            Dim responce As MsgBoxResult
            responce = MsgBox("Do you want to save changes to " & StatusWorksheet.Text & " ?", MsgBoxStyle.YesNoCancel, Me.Text)
            If responce = MsgBoxResult.Cancel Then
                continue = False
            ElseIf responce = MsgBoxResult.No Then
                worksheetModified = False
                continue = True
            ElseIf responce = MsgBoxResult.Yes Then
                mnuSaveAs.PerformClick()
                worksheetModified = False
                continue = True
            End If
        End If
    End Sub
This works well with every part of the program except for the Form1 close button "X". I wrote a closing sub for Form1 closing with the code:
Visual Basic:
    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        checkSave()
        If continue = False Then Exit Sub
        If continue = True Then MyBase.Dispose()
    End Sub
The problem is that the form closes when the message box cancel button is chosen and continue = False. Why?

Thanks
 
Last edited by a moderator:
Visual Basic:
    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If continue = False Then
            e.Cancel = True
        Else
            Me.Dispose()
        End If
    End Sub
You need to set e.Cancel = True to make it stop closing.
 
AS a side note....

I noticed you're using lots of member variables, you can eliminate continue by doing this...
Visual Basic:
 Function checkSave() as boolean
        If worksheetModified = True Then
            Dim responce As MsgBoxResult
            responce = MsgBox("Do you want to save changes to " & StatusWorksheet.Text & " ?", MsgBoxStyle.YesNoCancel, Me.Text)
            If responce = MsgBoxResult.Cancel Then
                return False
            ElseIf responce = MsgBoxResult.No Then
                worksheetModified = False
                return True
            ElseIf responce = MsgBoxResult.Yes Then
                mnuSaveAs.PerformClick()
                worksheetModified = False
                return True
            End If
        End If
    End Sub

Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If not checkSave Then
            e.Cancel = True
        Else
            Me.Dispose()
        End If
    End Sub
 
Back
Top