如何将datagridview空单元格保存到数据库表

时间:2016-05-31 20:11:07

标签: vb.net

有人可以告诉我如何使用带有空白单元格的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 ex As SqlException之间时,我收到错误 具有ParameterName' @ Col1'的OleDbParameter此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

1 个答案:

答案 0 :(得分: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

这应该就是你所需要的。注意 - 您需要设置参数大小的唯一时间是输出参数。在输入时,当您添加值时,大小会自动设置。但请记住在从参数中检索 string 数据时设置大小。