How do I delete the data in database based on the selected row in the datagridview? I've tried my query but its only deleted the data on tblproduct_stocks table
. I want to delete the data on the two table based on the product code and product size. By the way, I'm using ON DELETE CASCADE. Thanks for you help.
TABLE
--Table Structure for Products
CREATE TABLE tblproducts (
product_code varchar(50) NOT NULL PRIMARY KEY,
product_name varchar(100) NOT NULL,
product_supplier varchar(50) NOT NULL,
product_price int NOT NULL
);
--Table Structure for Products Stock In
CREATE TABLE tblproducts_stocks (
product_stocks_id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
product_size varchar(30) NOT NULL,
product_stocks int NOT NULL,
product_status varchar(50) NOT NULL,
Date varchar(100) NOT NULL,
Month varchar(100) NOT NULL,
Year varchar(100) NOT NULL,
product_code varchar(50) FOREIGN KEY REFERENCES tblproducts(product_code) ON DELETE CASCADE
);
QUERY
Public Sub deleteProducts()
productsView.btnDeleteProduct.Text = MessageBox.Show("Are you sure do you want to delete the selected product?", "WARNING: DELETION OF PRODUCT!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If productsView.btnDeleteProduct.Text = DialogResult.Yes Then
productsView.btnDeleteProduct.Text = "Delete"
Try
dbConnection()
Dim product_code As String = productsView.productsDGV.SelectedRows(0).Cells("product_code").Value
Dim product_size As String = productsView.productsDGV.SelectedRows(0).Cells("product_size").Value
delete_query = "DELETE FROM tblproducts_stocks WHERE product_size = @product_size AND product_code = @product_code;"
command = New SqlCommand
With command
.Connection = connection
.CommandText = delete_query
.Parameters.Add("@product_code", SqlDbType.VarChar, 50).Value = product_code
.Parameters.Add("@product_size", SqlDbType.VarChar, 30).Value = product_size
result = .ExecuteNonQuery()
If result = 0 Then
MsgBox("Error in deleting product!")
Else
MsgBox("Successfully deleted the selected product!")
End If
End With
Catch ex As SqlException
MsgBox("Error : " + ex.Message)
Finally
connection.Close()
command.Dispose()
retrieveProducts()
End Try
Else
productsView.btnDeleteProduct.Text = "Delete"
End If
End Sub