DataTable Delete Row and AcceptChanges

Posted by Pang on Stack Overflow See other posts from Stack Overflow or by Pang
Published on 2013-10-22T09:18:36Z Indexed on 2013/10/22 9:54 UTC
Read the original article Hit count: 284

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about datatable