2014-10-04 104 views
1

我有一個數據的數據網格。第一列是與進口商的組合框,第二列是進口數量。我希望能夠將這些數據保存到數據庫,而不管用戶的選擇。保存Datagrid數據到VB.Net中的SQL Server數據庫

請看我的代碼如下。有人可以幫我嗎?

Dim intReturnValue As Integer = 0 

Dim SqlCmd As String = "Update Importer_Balance SET Quantity = Quantity + @Quantity WHERE [email protected] and [email protected]" 

Dim ConnObj As SqlConnection = New SqlConnection(clsGlobals.ConnString) 
Dim CmdObj As SqlCommand = New SqlCommand(SqlCmd, ConnObj) 

For i = 0 To Me.dgvImporter.RowCount - 1 
     CmdObj.Parameters.AddWithValue("@Importer", Me.dgvImporter.Rows(i).Cells(0).Value) 
     CmdObj.Parameters.AddWithValue("@Quantity", Me.dgvImporter.Rows(i).Cells(1).Value) 
     CmdObj.Parameters.AddWithValue("@Product", cboProductName.SelectedValue) 
Next 

ConnObj.Open() 

intReturnValue = CInt(CmdObj.ExecuteNonQuery()) 

ConnObj.Close() 

If intReturnValue > 0 Then 
     MsgBox("You have successfully updated the product table product.", MsgBoxStyle.Information, "") 
     ClearForm() 
Else 
     MsgBox("No Record were inserted", MsgBoxStyle.Exclamation, "") 
End If 

回答

1

您添加的參數,但不執行命令的循環中,這會如果你只有一個行會產生錯誤,如果你要更新多行才起作用。
您繼續在每個循環讀取相同的參數到相同的命令。

取而代之的是,在循環之前和循環內移動參數的聲明,只需設置它們的值然後執行命令。

Dim intReturnValue As Integer = 0 
Dim SqlCmd As String = "Update Importer_Balance SET Quantity = Quantity + @Quantity WHERE [email protected] and [email protected]" 

Dim ConnObj As SqlConnection = New SqlConnection(clsGlobals.ConnString) 
Dim CmdObj As SqlCommand = New SqlCommand(SqlCmd, ConnObj) 
CmdObj.Parameters.Add("@Importer", SqlDbType.Int) 
CmdObj.Parameters.Add("@Quantity", SqlDbType.Int) 
CmdObj.Parameters.Add("@Product", SqlDbType.Int) 
ConnObj.Open() 

For i = 0 To Me.dgvImporter.RowCount - 1 
    CmdObj.Parameters("@Importer").Value = Convert.ToInt32(Me.dgvImporter.Rows(i).Cells(0).Value) 
    CmdObj.Parameters("@Quantity").Value = Convert.ToInt32(Me.dgvImporter.Rows(i).Cells(1).Value) 
    CmdObj.Parameters("@Product").Value = Convert.ToInt32(cboProductName.SelectedValue) 
    intReturnValue = CInt(CmdObj.ExecuteNonQuery()) 

Next 

重要說明:AddWithValue發現查看傳遞值的參數的數據類型。這種假設是危險的,可能會導致錯誤。最好使用專門的構造函數,您可以在其中定義參數的類型和大小

+0

Steve。感謝您的迴應。審查我的代碼並按照你的建議後,我得到這個錯誤:無法投入'System.Int32'類型的對象鍵入'System.Data.SqlClient.SqlParameter'。 – 2014-10-04 14:11:57

+0

我的不好,缺少最後一個參數中的值 – Steve 2014-10-04 14:12:42

+0

在您的回覆之前,我將整個代碼放在循環中。我得到的錯誤與我在遵循該指示後收到的錯誤類似。錯誤是:參數化查詢'(@Importer nvarchar(4000),@ Quantity nvarchar(4000),@ Product int)'需要參數'@Importer',該參數未提供。 – 2014-10-04 14:19:23

相關問題