我有一个DataGridView绑定到BindingSource对象的表单,该对象连接到使用Autonumber作为ID字段的Access数据库。
当编辑,删除或创建记录时,我运行DataAdapter的更新方法,该方法运行良好。但是新记录不会显示其ID,并且尝试删除新记录会导致DBConCurrencyException。
有没有办法告诉BindingSource,Databable或Dataset刷新/重新加载记录?显示新记录的自动编号ID的最佳方法是什么?
(警告,我知道这写不好,代码很抽象。)
Private conString As String = "Provider=Microsoft.ACE.OLEDB.12.0; " +
"Data Source=C:\data.accdb"
Private conn As OleDbConnection
Private WithEvents da As OleDbDataAdapter
Private ds As DataSet
Private builder As OleDbCommandBuilder
Private WithEvents bs As BindingSource
Private Sub AccessDataGridView_Load(sender As Object, e As EventArgs) Handles Me.Load
dgv1.AutoGenerateColumns = True
Call GetData("SELECT * FROM lots")
dgv1.DataSource = bs
dgv1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Function GetData(sSQL As String)
If conn Is Nothing Then
conn = New OleDbConnection
conn.ConnectionString = conString
conn.Open()
End If
da = New OleDbDataAdapter(sSQL, conn)
builder = New OleDbCommandBuilder(da)
ds = New DataSet
da.Fill(ds)
bs = New BindingSource
bs.DataSource = ds.Tables(0)
End Function
Private Sub bs_CurrentItemChanged(sender As Object, e As EventArgs) Handles bs.CurrentItemChanged
If ds.HasChanges() = True Then
da.Update(CType(bs.DataSource, DataTable))
End If
End Sub
Private Sub bs_ListChanged(sender As Object, e As System.ComponentModel.ListChangedEventArgs) Handles bs.ListChanged
If ds.HasChanges() = True Then
da.Update(CType(bs.DataSource, DataTable))
End If
End Sub
Private Sub da_RowUpdated(sender As Object, e As OleDbRowUpdatedEventArgs) Handles da.RowUpdated
If e.Status = UpdateStatus.Continue _
AndAlso e.StatementType = StatementType.Insert Then
Dim cmdGetIdentity As OleDbCommand
cmdGetIdentity = New OleDbCommand()
cmdGetIdentity.CommandText = "SELECT @@IDENTITY"
cmdGetIdentity.Connection = conn
e.Row("lotid") = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString())
e.Row.AcceptChanges()
'This appears to work with no problem, but the DataGridView
'still doesn't show the new ID
'EDIT
dgv1.Refresh() 'This fixed the problem mentioned directly above
End If
End Sub
答案 0 :(得分:1)
使用SqlClient时自动生成的ID传播回DataTable的方法是在InsertCommand的CommandText中包含SELECT语句。 Jet和ACE OLE DB提供程序不支持每个命令多个语句,因此这不是一个选项。我已经在另一个网站上专门为Access编写了一些示例代码但是现在它已经关闭,所以我无法给你链接。这是另一个例子:
http://support.microsoft.com/kb/816112/en-gb
该代码是C#但原理完全相同:处理数据适配器的RowUpdated事件,从数据库中获取ID并更新DataRow。