Joy1979 Joy1979 - 10 months ago 105
Vb.net Question

Delete records from SQL table in VB.Net

I am trying to delete records from my table but unable to do so. I have window form with Insert, Update, Delete and Save button. I can insert data but I can't delete specific or any records from that table. Below is my code.

Whenever I click 'delete' button I get ("Error while deleting record on table..." & ex.Message, "Delete Records") msgbox only.

Am I missing something? Please advise. Any help would be great. Thank you!

Private Sub Deletebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Deletebtn.Click

Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Server=USRAG-L-0067215\SQLEXPRESS;Database=Alamo Products_Design Data;Trusted_Connection=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "Delete From Design_Parameters where DesignID= ? "
cmd.ExecuteNonQuery()
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then

MsgBox("Operation Cancelled")

Exit Sub

End If
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")

Finally

con.Close()
End Try
End Sub


End Class

Answer Source

you need to add parameter for DesignID

Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Try
        con.ConnectionString = "Server=USRAG-L-0067215\SQLEXPRESS;Database=Alamo Products_Design Data;Trusted_Connection=True"
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "Delete From Design_Parameters where DesignID= @DesignID"
    cmd.Parameters.Add(New SqlParameter("@DesignID", yourvaluehere))
        cmd.ExecuteNonQuery()
        If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then

            MsgBox("Operation Cancelled")

            Exit Sub

        End If
    Catch ex As Exception
        MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")

    Finally

        con.Close()
    End Try
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download