从未绑定的datagridview创建数据表

时间:2014-06-10 15:11:08

标签: sql vb.net datagridview datatable

我想要一个创建数据表的按钮,然后批量复制到SQL数据库。我已经能够合并从SQL表创建的数据表开始的数据表,但我无法从头开始创建数据表。

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

    Dim table As New DataTable
    Dim row As DataRow

    Dim TableName As String = "SQLLocation_"

    table.Columns.Add(TableName & "Number", GetType(Int64))
    table.Columns.Add(TableName & "AnotherNumber", GetType(Int16))
    table.Columns.Add(TableName & "Name", GetType(String))
    table.Columns.Add(TableName & "Port", GetType(Int32))
    table.Columns.Add(TableName & "OnOff", GetType(Boolean))

    For Each drthree As DataGridViewRow In DataGridView3.Rows
        row = table.NewRow 'Create new row
        table.Rows.Add(row)
    Next

End Sub

此代码只会创建一堆空白行。最后,我将添加此代码以创建新表。

Using destinationConnection As SqlConnection = _
                   New SqlConnection(sConnectionString)
        destinationConnection.Open()

        ' Set up the bulk copy object.  
        ' The column positions in the source data reader  
        ' match the column positions in the destination table,  
        ' so there is no need to map columns. 

        Using bulkCopy As SqlBulkCopy = _
          New SqlBulkCopy(destinationConnection)
            bulkCopy.DestinationTableName = _
            "dbo.SQLLocation_Tbl"

            Try
                ' Write from the source to the destination.
                bulkCopy.WriteToServer(table)

            Catch ex As Exception
                MessageBox.Show(ex.ToString, _
            "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                System.Threading.Thread.CurrentThread.Abort()
            Finally
                ' Close the SqlDataReader. The SqlBulkCopy 
                ' object is automatically closed at the end 
                ' of the Using block.
            End Try
        End Using

    End Using
End Sub

1 个答案:

答案 0 :(得分:2)

这将允许您遍历datagridview并根据其列和行创建表。它会在数据表中创建具有相同名称的列,而不是像您尝试的那样。

        Dim table As New DataTable()
        For Each col As DataGridViewColumn In dgv.Columns
            table.Columns.Add(col.Name, col.ValueType)
            table.Columns(col.Name).Caption = col.HeaderText
        Next

        For Each row As DataGridViewRow In dgv.Rows
            Dim drNewRow As DataRow = table.NewRow()
            For Each col As DataColumn In table.Columns
                drNewRow(col.ColumnName) = row.Cells(col.ColumnName).Value
            Next
            table.Rows.Add(drNewRow)
        Next

如果要求使用其他名称,您可以保留当前创建列的方法,但是当您循环创建每一行时,您必须知道哪些列值与您想要的值匹配并映射它们而不是使用它们内心为每个人。

类似的东西:

  drNewRow("SQLLocation_Number") = row.cell(dgv.Columns(0).ColumnName).Value