Matt Wilko
Matt Wilko

Reputation: 27322

FormClosing Event Firing before I call Me.Close

I have a form (frmMain) that opens up another form (frmEdit) modally.

This in turn opens up a third form (frmSelection) modally.

My problem is that when frmSelection is closed, frmEdit also closes, yet nothing is actually closing it in my code.

Note the FormClosing and FormClosed events fire in the frmEdit

The code in frmMain

Using edit as New frmEdit
    edit.ShowDialog
End Using

The code in frmEdit:

Private Sub btnEditSelectionCriteria_Click(sender As Object, e As EventArgs) Handles btnEditSelectionCriteria.Click
    Using sel As New frmSelection
        sel.ShowDialog
    End Using
End Sub

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    Me.Close ' this is not called (breakpoint is not hit)
End Sub

Private Sub frmEditTask_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    'This fires when OK button clicked in frmSelection
End Sub

The code in frmSelection:

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    Me.Close ' this causes the FormClosing event to fire in frmEdit
End Sub

How can I track down what is closing my form? I thought there may be an exception being thrown but I checked Thrown in Common Language Runtime Exceptions to no avail.

Upvotes: 1

Views: 575

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27322

I found the source of this head scratcher - thanks to @Idle_Mind for the pointer:-

My button btnEditSelectionCriteria had the DialogResult property set to Cancel

This is actually a gotcha. If you create a button on a form then set the CancelButton property of the Form to be this button, it changes the DialogResult property of that button to Cancel.

This is what I had done, then I copied and pasted the cancel button to btnEditSelectionCriteria and this had retained the DialogResult property of Cancel

Upvotes: 1

Related Questions