DataGridView with dataadapter causes concurrency error when updating an add

Viewed 8

I am trying to replicate the action of a MSAccess table editor or the table editor in SSMS in a .NET desktop program with a SQL Server backend. I have created the datagridview, dataset, dataadapter, bindingsource and all the plumbing and am performing updates with the DataAdapter when the current row of the BindingSource changes. This all works fine. Records can be updated, deleted and added and are updated in the database as they happen. My table has an identity column

My problem is: if a record is added and then the user changes the row just added, I get a concurrency error. I assume this is because the identity column is not updated with the actual database identity value so the subsequent update fails (it is using the -1, -2 value in the datatable that is created with the new row)

How can I refresh the single row in the datatable that was inserted to have the correct value? Some suggestions I've seen say to refill the datatable with the adapter. The only problem with this is that it retrieves all the data and resets the current position in the datagridview. Also, I can't do that within the CurrentChanged event of the BindingSource.

Somehow Access and SSMS handle this issue. Any suggestions?

This is the code in my form. The dataadapter uses the automatically generated commands the Visual Studio creates.

Public Class frmBSPCOExclusions

' Minimum Code to get a Data Grid to work properly

Private _LastDataRow As DataRow = Nothing

Private Sub UpdateRowToDatabase()

    If _LastDataRow IsNot Nothing Then
        If _LastDataRow.RowState = DataRowState.Modified Or
           _LastDataRow.RowState = DataRowState.Added Or
           _LastDataRow.RowState = DataRowState.Deleted Then
            Me.Tbl_BSPCOSpecsTableAdapter.Update(_LastDataRow)
        End If
    End If

End Sub

Private Sub frmBSPCOExclusions_Load(sender As Object, e As EventArgs) Handles Me.Load

    Me.Tbl_BSPCOSpecsTableAdapter.Fill(Me.DsBSPCOSpecs.tbl_BSPCOSpecs)

End Sub

Private Sub frmBSPCOExclusions_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

    Me.dgvSpecs.EndEdit()
    Me.DsBSPCOSpecsBindingSource.EndEdit()
    UpdateRowToDatabase()

End Sub

Private Sub DsBSPCOSpecsBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles DsBSPCOSpecsBindingSource.CurrentChanged

    Dim _bs As BindingSource = DirectCast(sender, BindingSource)
    Dim _ThisDataRow As DataRow = DirectCast(_bs.Current, DataRowView).Row

    If _ThisDataRow Is _LastDataRow Then
        Exit Sub
    End If

    UpdateRowToDatabase()

    _LastDataRow = _ThisDataRow

End Sub

End Class

Thanks

0 Answers
Related