2016-05-31 79 views
-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 

回答

0

你做太多與你插入包含。您只需調用Parameters.AddWithValue即可,但此處的關鍵是將您的對象值轉換/轉換爲DB匹配的數據類型。假設兩個值都是varchar並且可以爲空。見代碼註釋

nonqueryCommand.CommandText = _ 
    "INSERT INTO myTable (Col1, Col2) VALUES (@Col1, @Col2)" 

' Prepare Parameters with correct Data Type 

nonqueryCommand.Parameters.AddWithValue("@Col1", String.Empty) 
nonqueryCommand.Parameters.AddWithValue("@Col2", String.Empty) 

For Each row As DataGridViewRow In DataGridView1.Rows 
    If Not row.IsNewRow Then 
     nonqueryCommand.Parameters(0).Value = 
      If(row.Cells(0).Value Is Nothing, DbNull.Value, row.Cells(0).Value.ToString()) 
     nonqueryCommand.Parameters(1).Value = 
      If(row.Cells(1).Value Is Nothing, DbNull.Value, row.Cells(0).Value.ToString()) 

     ' Here Execute your query for each row 
     If nonqueryCommand.ExecuteNonQuery() > 0 Then 
      Debug.WriteLine("Inserted Values") 
     End If 
    End If 
Next 

這應該是你所需要的。注 - 只有當您有輸出參數時,才需要設置參數的大小。在輸入時,大小會在您添加值時自動設置。但請記住在檢索字符串時要設置大小來自參數的數據。

+0

非常感謝您的回覆。它現在有效 – alex

+0

@alex它是否正在解決我的問題? –

相關問題