How to insert data from a datagridview to a sql query table?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi all,
im using the snippet reported here below to insert data from a datagridview to a sql table, but during debugging Im askin to "You must declare the scalar variable @T1" ... whats wrong in this snippet?
Thanks for your help.
V.If ToolStripTextBox1.Text <> "" Then
Dim con As New SqlConnection
Dim cmd As New SqlCommand

con.ConnectionString = sqlcon
con.Open()
Saving_Monograph.Show()

Try
cmd.Connection = con
cmd.CommandText = "insert INTO Table1 (ID, [T1], [T1_1] VALUES (" & ToolStripTextBox1.Text & ", @T1, @T1_1)"
cmd.ExecuteNonQuery()
adding parameter
cmd.Parameters.Add("@T1", SqlDbType.NVarChar, 2000)
cmd.Parameters.Add("@T1_1", SqlDbType.Float)
cmd.Prepare()
data inserting
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
cmd.Parameters("@T1").Value = row.Cells(0).Value
cmd.Parameters("@T1_1").Value = row.Cells(1).Value

End If

Next
cmd.ExecuteNonQuery()

Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try

ElseIf ToolStripTextBox1.Text = "" Then
MessageBox.Show("Please enter value in the textbox before to save.", "Error ...", MessageBoxButtons.OK)
End If
End Sub

View the full article
 
Back
Top