Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
5.00/5 (1 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
VB.NET
 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:
VB.NET
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

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 ...
 
Share this answer
 
Try to go in reverse order while looking for row to delete to avoid skipping a row after deleting the current index.
VB
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!
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900