Click here to Skip to main content
15,922,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to make a 'do you want to leave?' message. It is a yes/no question and if the answer is yes it leaves, but then if I say no, it will quit as well.
What is going wrong?
VB
MessageBox.Show("Do you really want to leave?", "Exiting.", MessageBoxButtons.YesNo)
        If Windows.Forms.DialogResult.Yes Then
            End
        ElseIf Windows.Forms.DialogResult.No Then
            Exit Sub
        End If
Posted

The predicate of your if-Statement has a constant value, namely Windows.Forms.DialogResult.Yes and that apparently counts as True. So the first branch gets always executed no matter what. In other words, you don't actually check for the result of the MessageBox.Show(..)-Method. You need to capture its return value and compare that to Windows.Forms.DialogResult.Yes :

VB
Dim result As Windows.Forms.DialogResult
result = MessageBox.Show("Do you really want to leave?", "Exiting.", MessageBoxButtons.YesNo)
If result = Windows.Forms.DialogResult.Yes Then
    End
Else
    Exit Sub
End If
 
Share this answer
 
v2
Instead of saving result into a variable you can directly use it in If condition and check user action. Please refer below code :
VB
If MessageBox.Show("Do you really want to leave?", "Exist", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
       End 'If User Select Yes
Else
       Exit Sub 'If User Select No
End If
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900