-1

My code does not remove any row from the database. These rows were shown in the listview in forms. They can be remove and disappear from the listview in the form but they are not removed from the database table.

Also, Im using MS Access for the database.

Here's the code

 Public Sub DeleteProduct()

        If ListView1.SelectedIndices.Count <= 0 Then
            Return
        End If

        Dim ItemNo As Integer = ListView1.SelectedIndices(0)
        Try
            Dim I As Integer = MsgBox("Are you sure you want to delete this record? You can't Undo", MsgBoxStyle.YesNo, "Are you sure?")
            If I = MsgBoxResult.Yes Then
                conn.Open()
                Dim cmd2 As New OleDb.OleDbCommand("DELETE FROM PRODUCT WHERE product_id = '" & ListView1.Items(ItemNo).SubItems(0).Text & "'", conn)
                cmd2.ExecuteNonQuery()
                MsgBox("Record removed successfully", MsgBoxStyle.OkOnly, "Remove Succeeded")
            Else
                Return
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
        End Try
        Refresh()

    End Sub
13
  • 3
    Use parameters - otherwise an apostrophe in your .Text property will break everything.
    – Dai
    Commented Nov 30, 2021 at 10:19
  • 2
    MsgBox("Record removed successfully" <-- This is wrong. You need to check the return-value of ExecuteNonQuery first to verify that a row was deleted instead of simple assuming that it was successful.
    – Dai
    Commented Nov 30, 2021 at 10:20
  • Unrelated: have you thought about implementing soft deletes instead? That way you can undo deletes.
    – Dai
    Commented Nov 30, 2021 at 10:20
  • 1
    Most likely, ListView1.Items(ItemNo).SubItems(0).Text doesn't hold the value you expect, or product_id is a number, not text.
    – Gustav
    Commented Nov 30, 2021 at 10:23
  • please share error message if any thing. Commented Nov 30, 2021 at 10:36

1 Answer 1

3

Separate your user interface code from your database code.

Connections and commands need to have their Dispose methods called so they should be declared locally in a Using block. Get in the habit of using Parameters instead of concatenating strings to build sql statements.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ListView1.SelectedIndices.Count = 0 Then
        MessageBox.Show("You must select an item to delete.")
        Exit Sub
    End If
    If MessageBox.Show("Are you sure you want to delete this record? You can't Undo", "Are you sure?", MessageBoxButtons.YesNo) = DialogResult.Yes Then
        Dim ItemNo As Integer = ListView1.SelectedIndices(0)
        Dim ProductID = CInt(ListView1.Items(ItemNo).Text)
        Dim RecordsDeleted As Integer
        Try
            RecordsDeleted = DeleteProduct(ProductID)
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
        If RecordsDeleted = 1 Then
            MessageBox.Show("Record removed successfully", "Remove Succeeded")
            ListView1.Items.RemoveAt(ItemNo)
        Else
            MessageBox.Show("Record was not deleter")
        End If
    End If
End Sub

Private OPConStr As String = "Your connection string."

Public Function DeleteProduct(ID As Integer) As Integer
    Dim retval As Integer
    Using conn As New OleDbConnection(OPConStr),
            cmd As New OleDbCommand("DELETE FROM PRODUCT WHERE product_id = @ID", conn)
        cmd.Parameters.Add("@ID", OleDbType.Integer).Value = ID
        conn.Open()
        retval = cmd.ExecuteNonQuery
    End Using
    Return retval
End Function
2
  • Thank you for this but it shows an error that says "System.InvalidCastException: 'Conversion from string "Snacks" to type 'Integer' is not valid.'" on part of "Dim ProductID = CInt(ListView1.Items(ItemNo).Text)" Commented Dec 1, 2021 at 12:39
  • Normally an ID field is a number. Are you sure you want to delete all the items that are "Snacks"? What is the Primary Key? Is it displayed in the ListView? To delete a single record, you need the primary key to uniquely identity the record.
    – Mary
    Commented Dec 1, 2021 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.