通过DataGridView VB.net更新记录

时间:2013-12-15 03:44:04

标签: vb.net ms-access visual-studio-2012 datagridview

您好我正在vb.net和MS访问后端开发WinForm应用程序。使用datagridview我可以通过简单地设置datagridview的datasource属性来显示记录。但我不知道如何通过datagridview更新记录,在vb6中它很容易更新记录本身它会更新数据库中的数据,但是在vb.net中如何更新记录?我用以下代码在datagridview中显示记录..

Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim adpt As OleDbDataAdapter
Dim rs As DataTable

    conn = New OleDbConnection
    conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source="& Application.StartupPath & "\sample.mdb"
    conn.Open()


    adpt = New OleDbDataAdapter("select * from table1", conn)
    rs = New DataTable
    adpt.Fill(rs)
    Me.dgv.DataSource = rs

如果我修改datagridview中的数据,它将不会影响databaserecords。请帮帮我......

1 个答案:

答案 0 :(得分:0)

为了通过我的datagridview更新数据库中的记录,我使用了DataSet。

这是我用来填充数据集的代码:

Public Cnn As New OleDb.OleDbConnection
Public Cmd As New OleDb.OleDbCommand
Public DR As OleDbDataReader
Public DA As OleDbDataAdapter
Public DS As DataSet
Public DT As DataTable
Public cmdBld As OleDbCommandBuilder

Cmd = New OleDbCommand("SELECT * FROM table1", Cnn)

Cnn.Open()

DA = New OleDbDataAdapter(Cmd)

cmdBld = New OleDbCommandBuilder(DA)

DS = New DataSet()

DA.Fill(DS, "table1")

DataGridView1.DataSource = DS.Tables("table1").DefaultView

Cnn.Close()

这是用于将更改从datagridview保存到数据库的代码:

Me.Validate()

Me.DA.Update(Me.DS.Tables("table1"))

Me.DS.AcceptChanges()