prem
prem

Reputation: 3548

SetAdded and SetModified can only be called on DataRows with Unchanged DataRowState

I am trying to update the RowState of a DataTable rows to Added as it is required for inserting data using DbDataAdapter Update method in database. In my scenario, I am doing some modification in data of few rows of the DataTable which is changing its RowState to Modified.

Below is the function in VB.Net which I am using to change the RowState

Protected Sub SetRowAdded(ByVal DataTable As DataTable)
        For Each row As DataRow In DataTable.Rows
            If Not row.RowState = DataRowState.Added Then row.SetAdded()
        Next
End Sub

Because of the aforementioned scenario, I am getting below error while changing RowState

SetAdded and SetModified can only be called on DataRows with Unchanged DataRowState

Does anyone have any idea that how to get it fixed?

Upvotes: 1

Views: 3594

Answers (1)

prem
prem

Reputation: 3548

By doing some research, I am able to find out the answer myself.

The row state of DataTable can be changed to Unchanged by accepting all the modifications using DataTable.AcceptChanges() method. I have changed my code as shown below and it is working absolutely fine now.

Protected Sub SetRowAdded(ByVal DataTable As DataTable)
        'Accept pending changes, as only Unchanged rows can be changed to Added or Modified
        DataTable.AcceptChanges()

        For Each row As DataRow In DataTable.Rows
            If Not row.RowState = DataRowState.Added Then row.SetAdded()
        Next
 End Sub

Upvotes: 5

Related Questions