我已将Access数据库链接到我的程序。它按原样填充DataGridView,以便部分程序正常工作。但是,我正在尝试让DataGridView更新Access数据库文件,并对其进行任何更改,但在尝试修复我的代码或寻找替代解决方案无数次尝试后,我感到难过。
任何人都可以看到任何错误或我错过的东西会导致代码无法按预期运行吗?提前谢谢。
Imports System.Data.OleDb
Public Class frmDatabase
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub frmDatabase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Joe\Documents\Visual Studio 2012\Projects\school database viewer\school database viewer\dbSchoolDatabase.mdb"
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from tableStudentDetails", con)
da.Fill(dt)
dgvStudentDetails.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Joe\Documents\Visual Studio 2012\Projects\school database viewer\school database viewer\dbSchoolDatabase.mdb"
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from tableStudentDetails", con)
da.Update(dt)
con.Close()
End Sub
End Class
答案 0 :(得分:1)
只需在代码中添加OleDbCommandBuilder
即可Private Sub frmDatabase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Joe\Documents\Visual Studio 2012\Projects\school database viewer\school database viewer\dbSchoolDatabase.mdb"
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from tableStudentDetails", con)
Dim cb = new OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
dgvStudentDetails.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
da.Update(dt)
End Sub
此类是必需的,因为OleDbDataAdapter本身无法创建更新网格中新建/已删除或已更改行所需的DELETE / UPDATE / INSERT命令。还要记住,如果SELECT命令不返回表的主键,OleDbCommandBuilder无法构建所需的命令。在这种情况下,您需要手动构建自己的命令。
另请注意,正如@gordthompson在下面的评论中指出的那样,使用OleDbCommandBuilder采取的预防措施是添加CommandBuilder将在您的字段名称和表名称周围使用的特殊字符,以避免与保留关键字(如果表格中存在
)