我在VB中創建一個Windows窗體應用程序,它將統計datagridview控件中的行並將它們插入到SQL數據庫中。問題在於,每次單擊按鈕時,datagridview中的行數都不相同。我想從一個datagridview添加一個可變數量的項目到一個SQL數據庫
我需要發生的是每個datagridview行都會將項目名稱和項目數量插入到數據庫中。
下面是代碼:
Private Sub Button22_Click(sender As Object, e As EventArgs) Handles Button22.Click
Dim myconnect As New SqlConnection
myconnect.ConnectionString = "Data Source=SEA-1800033547\SQLEXPRESS;database=operations;
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO odrcmp (CustName, CustAddress,Phone,email,item1,item1qty,item2,item2qty,date) VALUES (@custname, @custaddress, @phone, @email,@item1,@item1qty,@item2,@item2qty,@date)"
myconnect.Open()
Try
mycommand.Parameters.Add("@custname", SqlDbType.NChar).Value = customername.Text
mycommand.Parameters.Add("@custaddress", SqlDbType.NChar).Value = customeraddress.Text
mycommand.Parameters.Add("@phone", SqlDbType.NChar).Value = phonenumber.Text
mycommand.Parameters.Add("@email", SqlDbType.NChar).Value = email.Text
mycommand.Parameters.Add("@date", SqlDbType.NChar).Value = Label1.Text
For i As Integer = 1 To DataGridView1.Rows.Count - 1
For Each row In DataGridView1.Rows
mycommand.Parameters.Add("@item" & i, SqlDbType.NChar).Value = DataGridView1.Rows(i).Cells(0).Value
mycommand.Parameters.Add("@item" & i & "qty", SqlDbType.NChar).Value = DataGridView1.Rows(i).Cells(2).Value
mycommand.Parameters.Clear()
Next
Next
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
myconnect.Close()
End Sub
當我沒有在代碼中mycommand.Parameters.Clear()行,它會說,還在尋找標值ITEM2,這導致我相信在某個地方循環被搞砸了。
當我添加mycommand.Parameters.Clear()它表示它正在尋找@custname。我相信那是因爲代碼循環通過。
我我剛剛刪除了我原來的答案,因爲我認爲這是不對的。什麼是嵌套循環的原因?你有'For i'循環,然後是'For each'循環。 –
首先,循環中的這一行「mycommand.Parameters.Clear()」將刪除所有參數。這就是爲什麼它說它需要@custname。其次,你爲什麼使用嵌套? – Han
@SteveLovell我做了嵌套循環試圖讓它工作。當我使用「for i」循環時,它會錯誤地聲明「必須聲明item1標量變量。通過」For Each Row「循環,我無法弄清楚如何讓變量與item一起工作。 「item」&row「它說:System.InvalidCastException:'操作符'&'沒有爲字符串」item「定義並鍵入'DataGridViewRow'。'。我很感激你在這方面與我一起工作! – Rich