extra row being added to table

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
 
J

Jonathan Boivin

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
 
A

Alex

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top