Compare and delete datatable row using C#:

pourcetrierge

New Member
I have two tables such as DTTable1 and DTTable2. It has the following records.DTTable1:\[code\] ItemID Specification Amount --------- --------------- --------- 1 A 10 1 B 20 1 C 30\[/code\]DTTable1:\[code\] ItemID Specification Amount --------- --------------- --------- 1 A 10 1 B 20 1 C 30 2 A 10 2 B 20 3 A 10 3 B 20\[/code\]Here I want to compare these two tables. If DTTable1 records present in DTTable2(consider only ItemID) then remove the corresponding rows which has the ItemID same as DTTable1.I have tried foreach and forloop. Using ForEach:\[code\] foreach (DataRow DR in DTTable2.Rows) { if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) { DTTable2.Rows.Remove(DR); } } DTTable2.AcceptChanges();\[/code\]It showed the error, "Collection was modified; enumeration operation might not execute". So I used For Loop, It also not given the desired result.Using For Loop:\[code\] for (int i = 0; i < DTTable2.Rows.Count; i++) { if (DTTable2.Rows["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) { DTTable2.Rows.RemoveAt(i); } } DTTable2.AcceptChanges();\[/code\]But sometimes, the second row doesn't remove from the table. I get the final DataTable as\[code\] ItemID Specification Amount --------- --------------- --------- 1 B 20 2 A 10 2 B 20 3 A 10 3 B 20\[/code\]How to solve this? What is the simplest method to do this?
 
Back
Top