-2
有人可以告訴我如何更新帶有空單元格的datagridview表嗎? 我已經在設計器中創建了一個帶有兩列的datagridview數據輸入表單。我想留下一列空白的一些單元格,並將表格中的空白單元格保存爲零。如果沒有空白單元格,我可以節省datagridview的內容轉換成表格如何將datagridview空單元格保存到數據庫表
Dim thisConnection As New SqlConnection()
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
Console.WriteLine("Connection Opened")
' Create INSERT statement with named parameters
nonqueryCommand.CommandText = _
"INSERT INTO myTable (Col1, Col2) VALUES (@Col1, @Col2)"
' Add Parameters to Command Parameters collection
nonqueryCommand.Parameters.Add("@Col1", SqlDbType.VarChar, 50)
nonqueryCommand.Parameters.Add("@Col2", SqlDbType.VarChar, 50)
' Prepare command for repeated execution
nonqueryCommand.Prepare()
' Data to be inserted
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
nonqueryCommand.Parameters("@Col1").Value = row.Cells(0).Value.ToString
nonqueryCommand.Parameters("@Col2").Value = row.Cells(1).Value.ToString
End If
Next
nonqueryCommand.ExecuteNonQuery()
Catch ex As SqlException
' Display error
Console.WriteLine("Error: " & ex.ToString())
Finally
' Close Connection
thisConnection.Close()
Console.WriteLine("Connection Closed")
End Try
我不知道這是爲了保存到表以檢查空單元格正確的方法。我得到一個錯誤,當我把try和catch前作爲SQLEXCEPTION 與參數名稱的OleDbParameter「@ Col1中」之間的代碼不受此OleDbParameterCollection
If row.Cells(0).Value.ToString IsNot Nothing Then
nonqueryCommand.Parameters("@Col1").Value = row.Cells(0).Value.ToString()
else
nonqueryCommand.Parameters("@Col1").Value = "0"
end if
非常感謝您的回覆。它現在有效 – alex
@alex它是否正在解決我的問題? –