DataTable Delete Row and AcceptChanges
- by Pang
DataTable DT
num type name
===================================
001 A Peter
002 A Sam
003 B John
public static void fun1(ref DataTable DT, String TargetType)
{
for (int i = 0; i < DT.Rows.Count; i++)
{
string type = DT.Rows[i]["type"];
if (type == TargetType)
{
/**Do Something**/
DT.Rows[i].Delete();
}
}
DT.AcceptChanges();
}
My function get specific data rows in datatable according to the TargetType and use their info to do something. After the datarow is read (match the target type), it will be deleted.
However, the row is deleted immediately after .Delete() execute, so the location of the next row (by i) is incorrect.
For example, if TargetType is A. When i=0, the "Peter" row is deleted after .Delete executed. Then when i=1, I suppose it will locate the "Sam" row but it actually located "John" row because "Peter" row is deleted.
Is there any problem in my codes?