Click here to Skip to main content
14,641,293 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have a Datatable (dtP) filled by an OledbDataAdapter(daP) from an Access database.
Textboxes on the Form are bound to the dtP
I have 4 buttons that allow me to move through the rows (Next,Previous,First and Last) and a buttons to Update changes in a row and another button to delete a row.
Everything works fine, I can add rows, change data in a row except I am not able to delete a row.
The delete button which calls the following:
>>> CurrID <<< is the indexed ID of the current row
 Private Sub bDel_Click(sender As Object, e As EventArgs) Handles bDel.Click
    For i As Integer = 0 To dtP.Rows.Count - 1
        Dim dr As DataRow = dtP.Rows(i)
        If dr("ID") = CurrID Then
            dr.Delete()
        End If
    Next
    dtP.AcceptChanges()
End Sub
the application goes through without giving any error,I’ve put a breakpoint on the dr.delete line to make sure it goes through it, and it does, but the row does not get deleted.
I also tried dr.remove instead of dr.delete it does not work neither.

Any ideas?

Thank you

What I have tried:

I have also tried:
Private Sub bDel_Click(sender As Object, e As EventArgs) Handles bDel.Click
    For i As Integer = 0 To dtP.Rows.Count - 1
        Dim dr As DataRow = dtP.Rows(i)
        If dr("ID") = CurrID Then
            dr.remove()
        End If
    Next
    dtP.AcceptChanges()
End Sub
Posted
Updated 24-Jul-20 1:09am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

Read the documentation: DataRow.Delete Method (System.Data) | Microsoft Docs[^]
It's pretty clear on what happens:
Quote:
If the RowState of the row is Added, the RowState becomes Detached and the row is removed from the table when you call AcceptChanges.

The RowState becomes Deleted after you use the Delete method on an existing DataRow. It remains Deleted until you call AcceptChanges. At this time, the DataRow is removed from the table.

Delete should not be called in a foreach loop while iterating through a DataRowCollection object. Delete modifies the state of the collection.

A deleted row can be undeleted by invoking RejectChanges.

Do also note the chunk I put in italics ...
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Try to go in reverse order while looking for row to delete to avoid skipping a row after deleting the current index.
For i As Integer = dtP.Rows.Count - 1 To 0
Dim dr As DataRow = dtP.Rows(i)
    If dr("ID") = CurrID Then 
        dr.Delete()
    End If
Next

dtP.AcceptChanges()

If above does not work, try with
dt.Rows.Remove(dr)
approach.


See if this works!
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100