Adrian Enriquez
Adrian Enriquez

Reputation: 8413

windows form not closing when message box is yes

This is my code:

Private Sub frmName_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If e.CloseReason = CloseReason.UserClosing Then
        If MessageBox.Show("Are you sure you want to logout?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then                   
            Me.Close()
        Else
            e.Cancel = True
        End If
    End If
End Sub

If I click no it will cancel the form closing, but when I click yes the message box will appear repeatedly. What i want to happen is when I click the close button, and clicked yes it will close the form. How can I fix this?

Upvotes: 0

Views: 2571

Answers (1)

Markus
Markus

Reputation: 22511

As the Form is already closing, there is no need to call Close() again. The following code should work:

Private Sub frmName_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If e.CloseReason = CloseReason.UserClosing Then
        If MessageBox.Show("Are you sure you want to logout?", _
                "Exit", MessageBoxButtons.YesNo, _
                MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then                   
            e.Cancel = True
        End If
    End If
End Sub

Upvotes: 1

Related Questions