Click here to Skip to main content
15,922,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am try to use the delete button to delete a selected row in the database which is displayed in vb.net by a datagrid...here is my code .i keep having an error

VB
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btndelete.Click
        'check for the selected item in list
        If Me.dgvdata.Rows.Count > 0 Then
            If Me.dgvdata.SelectedRows.Count > 0 Then
                Dim prdname As String = Me.dgvdata.SelectedRows(0).Cells("name").Value
                'open connection
                If Not cnn.State = ConnectionState.Open Then
                    cnn.Open()
                End If

                'delete data
                Dim cmd As New SqlCommand
                cmd.Connection = cnn
                cmd.CommandText = "DELETE FROM stock WHERE product_name=" & Name
                cmd.ExecuteNonQuery()
                'refresh data
                Me.RefreshData()

                'close connection
                cnn.Close()
            End If
        End If
    End Sub
Posted
Updated 15-Apr-13 8:30am
v2
Comments
DinoRondelly 15-Apr-13 14:32pm    
Whats the error?
[no name] 15-Apr-13 14:50pm    
Your query should be "DELETE FROM stock WHERE product_name='" & prdname & "'" whatever the error is.
phillmac 15-Apr-13 14:52pm    
i did use the prdname but it still gives me an error saying invalid column name on this part cmd.ExecuteNonQuery()

Looking at your code i think the problem is in your query,

VB
cmd.CommandText = "DELETE FROM stock WHERE product_name=" & Name


But i dont see Name declared anywhere,

I think you want to use prdname in your query
 
Share this answer
 
v2
Comments
phillmac 15-Apr-13 14:47pm    
i did use the prdname but it still gives me an error saying invalid column name on this part
(cmd.ExecuteNonQuery()
[no name] 15-Apr-13 14:49pm    
Is "product_name" the exact name of the column in the database?
phillmac 15-Apr-13 14:50pm    
yes it is
DinoRondelly 15-Apr-13 14:56pm    
Im gonna have to say you are either spelling it wrong or that column isnt in that table. The error is pretty straight forward.
[no name] 15-Apr-13 20:49pm    
He needs to add quotes, "DELETE FROM stock WHERE product_name='" & prdname & "'"
Without the error message, it's difficult to be sure, but the first thing that springs to mind is this:
VB
  Dim prdname As String = Me.dgvdata.SelectedRows(0).Cells("name").Value
...
  cmd.CommandText = "DELETE FROM stock WHERE product_name=" & Name

Did you mean to use Name in the query? Shouldn't it be prdname?


BTW: 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.
 
Share this answer
 
Comments
phillmac 15-Apr-13 14:49pm    
i did use the prdname but it still gives me an error saying invalid column name on this part cmd.ExecuteNonQuery()
OriginalGriff 15-Apr-13 14:55pm    
Try quoting the product:
cmd.CommandText = "DELETE FROM stock WHERE product_name='" & prdname & "'"
Or using parameterized queries.

[edit]"Name" changed to "prdname" - OriginalGriff[/edit]
phillmac 15-Apr-13 15:01pm    
thank you it worked
OriginalGriff 15-Apr-13 15:09pm    
You're welcome!
phillmac 15-Apr-13 15:16pm    
now am trying to update using this code
'update data in table
cmd.CommandText = "UPDATE stock " & _
" SET product_name=" & Me.Txtproductname.Text & _
", product_id='" & Me.Txtproductid.Text & "'" & _
", unit='" & Me.txtunit.Text & "'" & _
", price='" & Me.txtprice.Text & "'" & _
", item_type='" & Me.Txtitem_type.Text & "'" & _
", date_in='" & Me.txtdate_in.Text & "'" & _
" WHERE product_name=" & Me.Txtproductname.Tag
cmd.ExecuteNonQuery()
End If
the full correct code is :

Imports System.Data
Imports System.Data.SqlClient
Public Class sedit
    Dim ds, ds1, ds2 As DataSet
    Dim da, da2, da11, da3 As SqlDataAdapter
    Dim cmd, cmd1, cmd2, cmd3 As SqlCommand

    Dim cb As SqlCommandBuilder
    Dim drow, drow1 As DataRow
    Dim dr, dr1, dr2 As SqlDataReader
    Dim cnn As New SqlClient.SqlConnection
    Private Sub sedit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cnn = New SqlClient.SqlConnection
        cnn.ConnectionString = ("server=.;uid=sa;pwd=june;database=pos;integrated security=false")
        Me.RefreshData()
        Timer1.Interval = 100
        Timer1.Start()

    End Sub
    Private Sub timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Label1.Text = System.DateTime.Now

    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cmd As New SqlCommand("select * from stock where product_name like '%" + TextBox1.Text + "%'", cnn)

        Dim Adpt As New SqlDataAdapter(cmd)

        Dim ds As New DataSet()

        If (Adpt.Fill(ds, "stock")) Then

            dgvdata.DataSource = ds.Tables(0)

            MessageBox.Show("match found")

        Else

            MessageBox.Show("match not found")

        End If
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnclose.Click
        Me.Close()
    End Sub

    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdata.CellContentClick

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btndelete.Click
        'check for the selected item in list
        If Me.dgvdata.Rows.Count > 0 Then
            If Me.dgvdata.SelectedRows.Count > 0 Then
                Dim prdname As String = Me.dgvdata.SelectedRows(0).Cells("name").Value
                'open connection
                If Not cnn.State = ConnectionState.Open Then
                    cnn.Open()
                End If

                'delete data
                Dim cmd As New SqlCommand
                cmd.Connection = cnn
                cmd.CommandText = "DELETE FROM stock WHERE product_name='" & prdname & "'"
                cmd.ExecuteNonQuery()
                'refresh data
                Me.RefreshData()

                'close connection
                cnn.Close()
            End If
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnclear.Click
        Me.Txtproductname.Text = ""
        Me.Txtproductid.Text = ""
        Me.txtunit.Text = ""
        Me.txtprice.Text = ""
        Me.txtdate_in.Text = ""
        Me.Txtproductname.Tag = ""

        'enable button edit
        Me.btnEdit.Enabled = True
        'set button add to add label
        Me.btnAdd.Text = "Add"
        '
        Me.Txtproductname.Focus()
    End Sub
    Private Sub RefreshData()
        If Not cnn.State = ConnectionState.Open Then
            'open connection
            cnn.Open()
        End If

        Dim da4 As New SqlClient.SqlDataAdapter("SELECT product_name as [name], " & _
                                             "product_id as [id], unit, Price, date_in " & _
                                             " FROM stock ORDER BY product_name", cnn)
        Dim dt As New DataTable
        'fill data to datatable
        da4.Fill(dt)

        'offer data in data table into datagridview
        Me.dgvData.DataSource = dt

        'close connection
        cnn.Close()
    End Sub

    Private Sub Btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnadd.Click
        Dim cmd As New SqlCommand
        If Not cnn.State = ConnectionState.Open Then
            'open connection if it is not yet open
            cnn.Open()
        End If

        cmd.Connection = cnn
        'check whether add new or update
        If Me.Txtproductname.Tag & "" = "" Then
            'add new 
            'add data to table
            cmd.CommandText = "INSERT INTO stock(product_name, product_id, unit,price, item_type, date_in) " & _
                            " VALUES('" & Me.Txtproductname.Text & "','" & Me.Txtproductid.Text & "','" & _
                            Me.txtunit.Text & "','" & Me.txtprice.Text & "','" & _
                            Me.Txtitem_type.Text & "','" & Me.txtdate_in.Text & "')"
            cmd.ExecuteNonQuery()
        Else
            'update data in table
            cmd.CommandText = "UPDATE stock " & _
                  " SET product_name=@prodName " & _
                  ", product_id=@prodID" & _
                  ", unit=@unit" & _
                  ", price=@price" & _
                  ", item_type=@itemType" & _
                  ", date_in=@date" & _
                  " WHERE product_name=@prodTag"
            cmd.Parameters.AddWithValue("@prodName", Me.Txtproductname.Text)
            cmd.Parameters.AddWithValue("@prodID", Me.Txtproductid.Text)
            cmd.Parameters.AddWithValue("@unit", Me.txtunit.Text)
            cmd.Parameters.AddWithValue("@price", Me.txtprice.Text)
            cmd.Parameters.AddWithValue("@itemType", Me.Txtitem_type.Text)
            cmd.Parameters.AddWithValue("@date", Me.txtdate_in.Text)
            cmd.Parameters.AddWithValue("@prodTag", Me.Txtproductname.Tag)
            cmd.ExecuteNonQuery()
        End If
        'refresh data in list
        RefreshData()
        'clear form
        Me.Btnclear.PerformClick()

        'close connection
        cnn.Close()
    End Sub

    Private Sub Btnedit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnedit.Click
        If Me.dgvdata.Rows.Count > 0 Then
            If Me.dgvdata.SelectedRows.Count > 0 Then
                Dim product_name1 As String = Me.dgvdata.SelectedRows(0).Cells("name").Value
                'get data from database followed by product_name
                'open connection
                If Not cnn.State = ConnectionState.Open Then
                    cnn.Open()
                End If
                'get data into datatable

                Dim da11 As New SqlClient.SqlDataAdapter("SELECT * FROM stock where product_name= '" & product_name1 & "'", cnn)
                Dim dt As New DataTable
                da11.Fill(dt)

                Me.Txtproductname.Text = product_name1
                Me.Txtproductid.Text = dt.Rows(0).Item("product_id")
                Me.txtunit.Text = dt.Rows(0).Item("unit")
                Me.txtprice.Text = dt.Rows(0).Item("price")
                Me.Txtitem_type.Text = dt.Rows(0).Item("item_type")
                Me.txtdate_in.Text = dt.Rows(0).Item("date_in")


                Me.Txtproductname.Tag = product_name1
                'change button add to update
                Me.Btnadd.Text = "Update"
                'disable button edit
                Me.Btnedit.Enabled = False
                'close connection
                cnn.Close()
            End If
        End If
    End Sub
End Class
 
Share this answer
 
the correct update code is :
cmd.CommandText = "UPDATE stock " & _
" SET product_name=@prodName " & _
", product_id=@prodID" & _
", unit=@unit" & _
", price=@price" & _
", item_type=@itemType" & _
", date_in=@date" & _
" WHERE product_name=@prodTag"
cmd.Parameters.AddWithValue("@prodName", Me.Txtproductname.Text)
cmd.Parameters.AddWithValue("@prodID", Me.Txtproductid.Text)
cmd.Parameters.AddWithValue("@unit", Me.txtunit.Text)
cmd.Parameters.AddWithValue("@price", Me.txtprice.Text)
cmd.Parameters.AddWithValue("@itemType", Me.Txtitem_type.Text)
cmd.Parameters.AddWithValue("@date", Me.txtdate_in.Text)
cmd.Parameters.AddWithValue("@prodTag", Me.Txtproductname.Tag)
cmd.ExecuteNonQuery()
End If
 
Share this answer
 

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