Gurlal Singh
Gurlal Singh

Reputation: 17

How can i exit from my main form if multiple forms are open in vb.net?My code is not working

 'Exit from the main form & Display Message about the number of times Users rated.
    Private Sub ExitApp()
        Dim ans As DialogResult
        Dim cns As DialogResult
        ans = MessageBox.Show("Do you want to exit?", "Exit App", MessageBoxButtons.YesNo, MessageBoxIcon.Question)

        If ans = DialogResult.Yes Then

            cns = MessageBox.Show("Thanks for rating." & " " & "You have been rated" & " " & iOne1 & " " & "Times",
                              "Total Rating", MessageBoxButtons.OK, MessageBoxIcon.Information)

        ElseIf cns = DialogResult.OK Then

            me.close()

        End If

    End Sub

Upvotes: 0

Views: 41

Answers (3)

V.Deep
V.Deep

Reputation: 427

Use Nested if because you click on OK in next messagebox not the first one...

Dim ans As DialogResult
        Dim cns As DialogResult
        ans = MessageBox.Show("Do you want to exit?", "Exit App", MessageBoxButtons.YesNo, MessageBoxIcon.Question)

        If ans = DialogResult.Yes Then

            cns = MessageBox.Show("Thanks for rating." & " " & "You have been rated" & " " & iOne1 & " " & "Times",
                              "Total Rating", MessageBoxButtons.OK, MessageBoxIcon.Information)

            If cns = DialogResult.OK Then

                Me.Close()

            End If
        End If

Upvotes: 2

Fabio
Fabio

Reputation: 32445

You have wrong if .. else. Checking for second dialog result need to be nested inside first if else. where in your case ElseIf cns = DialogResult.OK Then will never be reached.

Private Sub ExitApp()
    Dim ans As DialogResult = MessageBox.Show("Do you want to exit?", 
                                              "Exit App", 
                                              MessageBoxButtons.YesNo, 
                                              MessageBoxIcon.Question)

    If ans = DialogResult.Yes Then

        Dim message As String = $"Thanks for rating. You have been rated {iOne1} times"
        Dim cns As DialogResult = MessageBox.Show(message,
                                                  "Total Rating", 
                                                  MessageBoxButtons.OK, 
                                                  MessageBoxIcon.Information)

        If cns = DialogResult.OK Then
            Me.Close()
        End If
    End If

End Sub

Do not declare all variables in the beginning of function. Declare them only when you need, if you declared cns only when you created it, then your ElseIf will not even compiles, so you will be noticed about your "bug" during compile time.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416121

Environment.Exit() should do what you need.

Upvotes: 0

Related Questions