Click here to Skip to main content
15,899,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, I have a form with 2 datagridview 1 is from my table products and the other one is from my Job table, now I want to save what is in the two datagridview in a single table. But my code is not working, I'm new doing programming so please I need some help thanks ohhhh and I got this error
Exception Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll ("Must declare the scalar variable "@d6".") System.Data.SqlClient.SqlException
thanks .

What I have tried:

Dim cb5 As String = "insert into Bill_Detail(InvoiceID,CustomerID,ProductID,Qty,ProductPrice,TotalAmount,ProductName,JobID,JobName,JobPrice) VALUES (" & txtST_ID.Text & "," & txtID.Text & ",@d1,@d2,@d3,@d4,@d5,@d6,@d7,@d8)"
cmd = New SqlCommand(cb5)
cmd.Connection = con
cmd.Prepare()
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
cmd.Parameters.AddWithValue("@d1", Val(row.Cells(0).Value))
cmd.Parameters.AddWithValue("@d2", Val(row.Cells(4).Value))
cmd.Parameters.AddWithValue("@d3", Val(row.Cells(3).Value))
cmd.Parameters.AddWithValue("@d4", Val(row.Cells(5).Value))
cmd.Parameters.AddWithValue("@d5", row.Cells(2).Value)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()

End If

Next
For Each row As DataGridViewRow In DataGridView2.Rows
If Not row.IsNewRow Then
cmd.Parameters.AddWithValue("@d6", Val(row.Cells(5).Value))
cmd.Parameters.AddWithValue("@d7", row.Cells(0).Value)
cmd.Parameters.AddWithValue("@d8", Val(row.Cells(1).Value))
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
End If
Next
con.Close()
Posted
Updated 23-Aug-17 14:14pm

1 solution

Your issue is self explanatory - you have declared parameters @d6, @d7 & @d8 but have not added them to your SQL Command prior to executing the query.
If you were to get past this first error - perhaps by setting the values to NULL, then you would get a similar error when you get to your second insert but the error would be "Must declare the variable @d1"

if you wanted to set the values to NULL in the respective insert statements you would do as follows;
VB
cmd.Parameters.AddWithValue("@d6", DBNull.Value)


Alternatively have 2 different Insert statements
 
Share this answer
 
v2
Comments
Member 13164214 23-Aug-17 20:31pm    
Thanks for your answer, Do you have any recommendations on how I can do it?, What I want is that whatever is in datagrid1 and datagrid2 be save in the Bill_detail table, thanks.
an0ther1 23-Aug-17 22:52pm    
Refer to the updated solution - if you cannot set the values to NULL you would need to set it to a value of the appropriate type (eg; 0 for an int, "" for a varchar etc)

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