【发布时间】:2014-02-09 23:11:36
【问题描述】:
我有一个表单,其 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
【问题讨论】:
标签: vb.net datagridview datatable ado.net bindingsource