You get this error because a collection must not change while iterating it. To remove some items from a collection you usually need a second collection that you iterate without changing it.
For your DataTable
you need to get the rows you want to remove first and put them in a new collection. One way to achieve this is with LINQ
:
Let's create some test data:
DataTable dt = new DataTable();
dt.Columns.Add("Test", typeof(bool));
DataRow dr1 = dt.NewRow();
DataRow dr2 = dt.NewRow();
DataRow dr3 = dt.NewRow();
dr1["Test"] = true;
dr2["Test"] = false;
dr3["Test"] = false;
dt.Rows.Add(dr1);
dt.Rows.Add(dr2);
dt.Rows.Add(dr3);
then only get rows where value in the Test
column is false
and put them in a List<DataRow>
:
var removeRows =
dt
.AsEnumerable()
.Where(r => (bool)r["Test"] == false)
.ToList();
now you can itereate the new removeRows
list and remove its items from the first collection (here DataTable.Rows
)
// Remove selected rows.
foreach (var row in removeRows)
{
dt.Rows.Remove(row);
}
In your this query should work:
var removeRows =
dtapple
.AsEnumerable()
.Where(r => string.IsNullOrEmpty(r["PassportExpDate"].ToString()) == false)
.ToList();
If you use string.IsNullOrEmpty()
there's no need to Trim()
it.