Msgbox Yes No & cancel button working in VB.NET 2010

CrashOverride picture CrashOverride · Mar 16, 2013 · Viewed 68.2k times · Source

Below is my code for a MsgBox. The Yes button is working, but when I click No or Cancel it still deletes the data...

        strup = "DELETE FROM student WHERE urno =" & CInt(txtUrn.Text) & ";"
        Dim command As New OleDb.OleDbCommand(strup, con)
        MsgBox("Do you want to delete record(s)", MsgBoxStyle.YesNoCancel, "Confirm Delete")
        command.ExecuteNonQuery()
        con.Close()

How do I have it cancel the delete operation when clicking No or Cancel?

Answer

PurkkaKoodari picture PurkkaKoodari · Mar 16, 2013

Use the basic If statement to check the return value of MsgBox. The MsgBox doesn't cancel anything by itself.

If MsgBox("Prompt", MsgBoxStyle.YesNoCancel, "Title") = MsgBoxResult.Yes Then
    ' execute command
End If

You could also use MsgBoxStyle.YesNo to get only the Yes and No buttons.