2014-08-30 85 views
0

我正在制作一个程序,我点击数据网格中的一个单元格,并将选定的字符串传递给另一个表单中的另一个数据集。这以后,随着数据集的形式有其ID(主键)值为-1我认为这是为什么我遇到的错误在更新使用vb.net更新ms访问问题关于主键是-1

我遇到的错误的原因是并发性问题,而不是空

请帮忙。我真的需要它

+1

提供关于您的代码和您所做的测试的更多细节将会很有用。 – 2014-08-30 18:39:04

回答

0

如果在Access中有一个主表键值为AutoNumber的主键,.NET DataTable中的相应列将按照您看到的方式工作,即它将生成临时PK值,该值在-1处生成并递增乘以-1。原因是为了确保生成的值不会与数据库中已有的PK值相同。您可以使用该PK作为应用程序中的外键来创建子记录。

当您将父记录保存到您的数据库时,它会生成最终的PK值,这是保存的内容,而不是您的临时值。此时,如果您在任何地方使用该临时值,则取决于数据库的最终值,然后将其传播到需要的任何位置。通常,它会通过DataRelation自动传播到同一DataSet中的一个或多个其他DataTable对象。

我想说你的第一个错误是在同一DataSet之外使用临时PK。如果你需要在其他地方使用PK,那么你应该首先保存数据,获得最终PK并使用它。如果你不能这样做,那么记录应该只在相同的DataSet之内。

你应该看看我的线程上获取Access AutoNumber值,并使用一个DataRelation传播他们:

http://www.vbforums.com/showthread.php?659052-Retrieve-Access-AutoNumber-Value-After-Insert

下面的代码从示例中的症结与类型化DataSet

''' <summary> 
''' Handles the RowUpdated event of the parent adapter. 
''' </summary> 
''' <param name="sender"> 
''' The adapter that saved the row. 
''' </param> 
''' <param name="e"> 
''' The data for the event. 
''' </param> 
''' <remarks> 
''' This event handler is used to retrieve an auto-generated ID from the database after a row is inserted and update the corresponding row in the local data set. 
''' </remarks> 
Private Sub parentAdapter_RowUpdated(sender As Object, e As OleDbRowUpdatedEventArgs) 
    'We are only interested in new records. 
    If e.StatementType = StatementType.Insert Then 
     'Get the last ID auto-generated by the database. 
     Dim lastAutoNumber = Me.parentAdapter.GetLastAutoNumber().Value 

     'Update the ID of the local row. 
     DirectCast(e.Row, ParentChildDataSet.ParentRow).ParentID = lastAutoNumber 
    End If 
End Sub 

''' <summary> 
''' Handles the RowUpdated event of the child adapter. 
''' </summary> 
''' <param name="sender"> 
''' The adapter that saved the row. 
''' </param> 
''' <param name="e"> 
''' The data for the event. 
''' </param> 
''' <remarks> 
''' This event handler is used to retrieve an auto-generated ID from the database after a row is inserted and update the corresponding row in the local data set. 
''' </remarks> 
Private Sub childAdapter_RowUpdated(sender As Object, e As OleDbRowUpdatedEventArgs) 
    'We are only interested in new records. 
    If e.StatementType = StatementType.Insert Then 
     'Get the last ID auto-generated by the database. 
     Dim lastAutoNumber = Me.childAdapter.GetLastAutoNumber().Value 

     'Update the ID of the local row. 
     DirectCast(e.Row, ParentChildDataSet.ChildRow).ChildID = lastAutoNumber 
    End If 
End Sub 

GetLastAutoNumber是在设计器中添加到表适配器的自定义标量查询,这是SQL代码:

SELECT @@IDENTITY