Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Similar to If...Then, but I think this is cleaner

Select Case MsgBox("Are you sure ?", MsgBoxStyle.YesNo, "Delete")
    Case MsgBoxResult.Yes
        ' Do something if yes
    Case MsgBoxResult.No
        ' Do something if no
End Select
        If MsgBox("Are you sure ?", MsgBoxStyle.YesNo, "Delete") = MsgBoxResult.Yes Then
            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()
            txtUrn.Text = ""
            txt10Per.Text = ""
            txt12Per.Text = ""
            txtCAdd.Text = ""
            txtEid.Text = ""
            txtFname.Text = ""
            txtGPer.Text = ""
            txtMno.Text = ""
            txtName.Text = ""
            txtPAdd.Text = ""
            cmb10YofPass.Text = ""
            cmb12YofPass.Text = ""
            cmbDate.Text = ""
            cmbGender.Text = ""
            cmbMonth.Text = ""
            cmbNameofGCourse.Text = ""
            cmbYear.Text = ""
            ComboBox1.Text = ""
            TextBox1.Text = ""
            MsgBox("Record Deleted Successfully")
        ElseIf MsgBoxResult.No Then

        End If

Still a MsgBox will not work in an ASP.NET production environment or QA rather than development environment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top