VB 2013:如何使用datagridview值更新数据库

时间:2015-03-18 01:46:08

标签: vb.net datagridview auto-update

我的表格中有一个可以编辑的DGV。我想将更新后的值写回数据库,以便下次读取时可以使用它们。

我搜索了网络周围的答案,并通过打开连接并更新它来找到了几种方法。但是,我想知道是否有使用单个命令更新数据库的直接方法。

我是VB的新手,只学习一个库项目,因此很难理解和实现代码中处理SQL的语句。请帮忙......谢谢

1 个答案:

答案 0 :(得分:0)

正确的方法是使用数据适配器填充然后绑定到网格的DataTable,然后使用相同的数据适配器将该表中的更改保存回数据库。 E.g。

Private adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Private builder As New SqlCommandBuilder(adapter)
Private table As New DataTable

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'Query the database and populate the DataTable.
    adapter.Fill(table)

    'Bind the data to the UI.
    BindingSource1.DataSource = table
    DataGridView1.DataSource = BindingSource1
End Sub

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    BindingSource1.EndEdit()

    'Save the changes back to the database.
    adapter.Update(table)
End Sub

BindingSource将添加到设计器中的表单中。

相关问题