I'm trying to insert multiple rows into an Access database. The table is named sales with the columns sandwich and price. The data I'm trying to insert is contained in multiple TextBox controls.
So far I've tried this code:
Dim sql As String = "INSERT INTO [sales] ([sandwich]) VALUES ([@sandwich])"
Try
Using conn As New OleDbConnection(constring)
Using cmd As New OleDbCommand(sql, conn)
conn.Open()
For Each Order As TextBox In grpbill.Controls
If Order.Text.Length > 0 Then
cmd.Parameters.AddWithValue("@sandwich", Order.Text)
cmd.ExecuteNonQuery()
End If
Next Order
End Using
conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
It's working fine. The program is checking for full TextBox controls only and inserting the correct number of rows however when I check the database the values are all the same, inserting the value of the last TextBox over and over.
Any ideas how to fix this?
grpbill.Controlsto begrpbill.Controls.OfType(Of TextBox)(). That way you know you're only ever going to deal with aTextBox. And you should consider adding your parameter before theForand then updating the value in each loop.cmd.parameters.clearbefore adding them. This will ensure you dont run into any exceptions with parameters already added.