2014-08-30 81 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