Using Message Box DialogResult.No Condition for closing the form doesnot perform as expected.
The formclosing event aske user whether to save the document or not before closing.
The following is my FormClosing event.
Private Sub PDFViewSimple_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
Handles Me.FormClosing
If doc.IsModified Then
Dim message As String = "The document is modified, would you like to save it?"
Dim caption As String = "File Not Saved"
Dim buttons As MessageBoxButtons = MessageBoxButtons.YesNo
Dim DefaultButton As MessageBoxDefaultButton = MessageBoxDefaultButton.Button1
Dim icon As MessageBoxIcon = MessageBoxIcon.Question
Dim result As DialogResult
' Displays A MessageBox.
result = MessageBox.Show(message, caption, buttons, icon, DefaultButton)
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
ElseIf (result = DialogResult.No) Then
Me.Close() ''Should I replace with (Application.Exit)
End If
End If
End Sub
There's all sorts wrong with that code. Firstly, given that there are only two options, using ElseIf
is pointless, although not strictly wrong. If it's not Yes
then it must be No
, so you'd only need an Else
:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
Else
Me.Close()
End If
Next, even an Else
is pointless because you're calling Close
regardless of the outcome. All you need to do is check for Yes
, do anything specific to Yes
and then call Close
regardless:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
Me.Close()
Finally, you shouldn't be calling Close
at all. You're in the FormClosing
event handler so the form is already closing. You only have to do something if you want the form to NOT close. So, all you need is this:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
If you wanted the form to NOT close then you would set e.Cancel
to True
.