extra row being added to table

  • Thread starter Thread starter Alex
  • Start date Start date
A

Alex

Whenever I run this code, I get an extra row added to my table with a
primary field text of "System.Object". This code is intended to
simply add a single row to a single table based on the value in the
tbOrd.text textbox. Instead, two rows are going in - one is intended,
the second is not. Anybody see why this is happening and what I need
to do to stop the extra row from being added.

Dim strNewOrder, strSQL As String
Dim rowToInsert As DataRow
Dim tbl As New DataTable("Orders")

tbl.Columns.Add("Order", GetType(String))
tbl.Columns.Add("ID", GetType(String))

strNewOrder = tbOrd.Text
strSQL = "INSERT INTO Orders " & _
" (Order) VALUES " & _
" (@Order)"

Dim da As New SqlDataAdapter(strSQL, cn)
da.SelectCommand.Parameters.AddWithValue("Order", strNewOrder)
da.Fill(tbl)

cn.Open()

rowToInsert = tbl.Rows.Add(New Object(), strNewOrder)

Dim cmdInsert As New SqlCommand(strSQL, cn)
cmdInsert.Parameters.AddWithValue("@Order",
rowToInsert("Order"))

Try
cmdInsert.ExecuteNonQuery()
rowToInsert.AcceptChanges()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

cn.Close()
End Sub

Thanks
 
When you are adding your row, you are not doing it correctly.
The method Add doesn't have two parameters. Only one which is an array of
values (Each for 1 column).

So you should change the tbl.Add to tbl.Add(New Object() {strNewOrder})

Jonathan Boivin
 
Thanks, Jonathan. Your suggestion was right. Once I changed that
line (and re-ran the app), the record that included the field
System.Object immediately changed to the correct value. However, I
still had an extra row - now the rows were identical. That tipped me
off that I was calling the add command twice. I took out the
cmdInsert.ExecuteNonQuery and everything is working as intended.

Thanks for your help.
 
Back
Top