Search code examples
.netvb.netvariablesmsgbox

Yes/No message box always returns yes - VB.Net


I was experimenting with message boxes, and tried a simple yes/no messagebox So I wrote this simple piece of code. However, the "chc" variable always returns as 1, no matter what button I press. I provided the code, so you maybe see what I did wrong. It is probably horribly wrong.

If MsgBoxResult.Yes Then
    chc = 1
ElseIf MsgBoxResult.No Then
    chc = 0
End If

MsgBox(chc)

Solution

  • The MsgBox() method is returning MsgboxResult Enumeration, check the value that the method returns:

    Public Sub MsgBoxExample()
        Dim result As MsgBoxResult = Nothing
        Dim chc As Integer
    
        result = MsgBox("click something...", vbYesNo, "example")
        If result = MsgBoxResult.Yes Then
            chc = 1
        ElseIf result = MsgBoxResult.No Then
            chc = 0
        End If
        MsgBox(chc)
    End Sub