如何将Datagrid数据存储到数据库

时间:2012-08-08 03:20:23

标签: vb.net datagrid

我想将datagrid值存储到数据库中。我有1列名为项目标题。我想将数据库中该列下的所有值添加到数据库...

2 个答案:

答案 0 :(得分:0)

您正在开发哪种语言?

vb.net中的示例:

For i As Integer = 0 To DataGridView1.Rows.Count

        Dim obj As Object = DataGridView1.Rows(i).Cells(0).Value

        ' save in database

 Next

您可以将obj转换为您自己的类型,然后将其保存在您的数据库中。

答案 1 :(得分:0)

这是填充DataGridViewDataTable

的初始代码
    Private bindingSource1 As New BindingSource()    
    Private dataAdapter As New OleDbDataAdapter()

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load    
        Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FilePath>;User Id=username;Password=password;"    
        Dim selectCommand As String    
        Dim connection As New OleDbConnection(connectionString)

        selectCommand = "SELECT * FROM...<YOUR SELECT Query>"    
        Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)

        Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)    
        Dim table As New DataTable()

        Me.dataAdapter.Fill(table)    
        Me.bindingSource1.DataSource = table

        Dim data As New DataSet()

        DataGridView1.DataSource = Me.bindingSource1    
    End Sub

这就是您想要的(使用DataAdapter将数据网格数据存储到数据库)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim table As New DataTable()

        Me.bindingSource1 = Me.DataGridView1.DataSource    
        table = Me.bindingSource1.DataSource

        Me.dataAdapter.Update(table)    
    End Sub

End Class