Click here to Skip to main content
15,884,628 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
VB
Private Sub BtnDelete_Click(sender As System.Object, e As System.EventArgs) Handles BtnDelete.Click
        If MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
            cnsql = "delete TbProduct where ProductID= "" & ProductID & """
            cn = New SqlClient.SqlConnection(cnstr)
            cn.Open()
            cm = New SqlClient.SqlCommand(cnsql, cn)
            dr = cm.ExecuteReader <----Error! it says Invalid column name ' & ProductID & '.
            ShowData()
            TxtProductNameD.Clear()
            TxtProductpriceD.Clear()
            BtnDelete.Enabled = False
        Else
            TxtProductNameD.Clear()
            TxtProductpriceD.Clear()
            BtnDelete.Enabled = False

        End If
    End Sub


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 17-Jan-15 2:28am
v2
Comments
Idle_Force 17-Jan-15 11:02am    
Why do we allow bad question titles - these are not searchable by any means.

Use parameter as below
C#
cnsql = "delete from TbProduct where ProductID=@ProductID"
cn = New SqlClient.SqlConnection(cnstr)
cn.Open()
cm = New SqlClient.SqlCommand(cnsql,cn)
cm.Parameters.AddWithValue("@ProductID",ProductID)
dr = cm.ExecuteReader
 
Share this answer
 
v2
Comments
Member 11381884 17-Jan-15 10:16am    
Thanks :D
VB
cnsql = "delete TbProduct where ProductID= "" & ProductID & """
cn = New SqlClient.SqlConnection(cnstr)
cn.Open()
cm = New SqlClient.SqlCommand(cnsql, cn)
dr = cm.ExecuteReader <----Error! it says Invalid column name ' & ProductID & '.
Um.
SQL DELETE operations do not return an SqlReader - only SELECT operations do that - so the system is confused as to what you are trying to do.

Try this instead:
VB
...
cm = New SqlClient.SqlCommand(cnsql, cn)
cm.ExecuteScalar
But the string looks wrong as well, and even if you fix it:
VB
cnsql = "DELETE FROM TbProduct WHERE ProductID= " & ProductID
You are leavign yourself wide open to SQL injection attacks. Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

[edit]"delete TbProduct..." changed to "DELETE FROM TbProduct..." - Oops...[/edit]
 
Share this answer
 
v2
Comments
DamithSL 17-Jan-15 8:41am    
OG, delete FROM is missing
OriginalGriff 17-Jan-15 9:04am    
Picky, picky, picky... :laugh:
Fixed, thanks!
Member 11381884 17-Jan-15 10:16am    
Thanks :D
OriginalGriff 17-Jan-15 10:17am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900