Search code examples
vb.netwinformsdialogabort

Aborting a dialog from within the dialog


There are 2 Forms FA and FB.
FA is the initial form and it issues FB.ShowDialog() to launch FB. FB starts well, but then encounters a problem and wishes to abort, returning control to FA.
I thought coding

Me.DialogResult = DialogResult.Cancel
Me.Close()

when FB hits the problem would do the trick. but no - the code rumbles on, and (presumably a logic error on my part) bumps into the same problem again, and again.
I will nail the logic problem, but is there no way of actually stopping the form dead - the equivalent of Me.AbortFormImmediately ?


Solution

  • Both the Comments are great and should help the person asking the question
    I am going to expand on this question with the thought that Closing forms happens two ways
    Either a BACK button is pressed to go to another form
    OR
    The TitleBar Close Button (the X) is selected
    Because I got tired of writing the code on each form to manage these process
    I added a Module to the project and added a Public Sub to do all the work

    With a little work this Module Code could be improved upon

    Here is the Relevant Code

    The Module

    Module ModuleOne
    Public Sub CloseTheForm()
        Const message As String = "YES Go To Form One" + vbCrLf + vbNewLine + "NO CANCEL"
        Const caption As String = "EXIT"
    
        Dim result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = DialogResult.Yes Then
            If frmThree.Visible Then
                frmThree.Hide()
                frmOne.Show()
            End If
            If frmFour.Visible Then
                frmFour.Hide()
                frmOne.Show()
            End If
    
        ElseIf result = DialogResult.No Then
            If frmThree.Visible Then
                frmThree.tbHaveTwo.Text = "CANCEL"
            End If
            If frmFour.Visible Then
                frmFour.tbFive.Text = "CANCEL"
            End If
        End If
    End Sub End Module
    

    Relevant Code for frmThree

        Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        tbHaveOne.Clear()
        CloseTheForm()
    End Sub
    
    Public Sub frmThree_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.Closing
        CloseTheForm()
        e.Cancel = True
    End Sub
    

    Code for frmFour

        Public Sub frmFor_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.Closing
        CloseTheForm()
        e.Cancel = True
    End Sub
    
    Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        tbFour.Clear()
        CloseTheForm()
    End Sub