I am working on in vb.net . Here i want to remove row of datatable using rowid. All is working fine but after remove row from datatable then i got a error message is Collection was modified; enumeration operation might not execute. I am using following code for delete row from datatable.
vb.net code:-
Dim dr As DataRow
For Each dr In dt.Rows
If dr("RowID").ToString() = dt.Rows(0)("RowID").ToString() Then
dt.Rows.Remove(dr)
End If
Next
For Each dr In dt.Rows
If dr("RowID").ToString() = dt.Rows(0)("RowID").ToString() Then
dt.Rows.Remove(dr)
End If
Next
VulpesPosted Nov 12, 2014, 5:06 AM
This is because each time you delete a row it alters the indices of the rows still to be examined which all move down one. If you iterate forwards, you will therefore fail to examine the next element in the collection.
Iterating backwards is the cleanest way to avoid this problem though you can still iterate forwards if you decrement the loop control variable before the next iteration.
Abhay ShankerPosted Nov 12, 2014, 3:47 AM
Jaganathan BantheswaranPosted Nov 12, 2014, 2:12 AM
Try to do something like this.
Dim dt1 As New DataTable()
dt1.Columns.Add("Name")
dt1.Rows.Add("Apple")
dt1.Rows.Add("Banana")
dt1.Rows.Add("Orange")
Dim dt2 As New DataTable()
dt2.Columns.Add("Name")
dt2.Rows.Add("Apple")
dt2.Rows.Add("Banana")
Dim rows_to_remove As New List(Of DataRow)()
For Each row1 As DataRow In dt1.Rows
For Each row2 As DataRow In dt2.Rows
If row1("Name").ToString() = row2("Name").ToString() Then
rows_to_remove.Add(row1)
End If
Next
Next
For Each row As DataRow In rows_to_remove
dt1.Rows.Remove(row)
dt1.AcceptChanges()
Next