Monday, April 4, 2016

Datatble Remove Rows C# while Looping

If you want to remove certain rows from a DataTable in C# and looping is easier to check the values to delete the FOR or FOREACH ROWS doesnt work because the count will be different once the Row is removed and it doesnt work.

So instead of using the following code which will fail

//Wrong Code dont use this .. this will Fail
            foreach (DataRow orow in dataTable.Rows)
                {
                    
                        if ((orow["ID"].ToString()).Equals("2"))
                        {
                            dataTable.Rows.Remove(orow);
                        }
                    
                }
Instead of using the above code use Select() as shown below

//Correct code use this
           foreach (DataRow orow in dataTable.Select())
                {

                    if ((orow["ID"].ToString()).Equals("2"))
                    {
                        dataTable.Rows.Remove(orow);
                    }

                }
Check this Fiddle
Leave a Comment. Bob