How delete rows from DataTable and avoid "no row at position" error?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
R

Ronald S. Cook

Consider the following DataTable:

FoodId FoodName FoodType
1 Apple Fruit
2 Pear Fruit
3 Corn Vegetable
4 Bread Starch
5 Cereal Starch
6 Carrot Vegetable
7 Grapes Fruit

I want to delete all records where FoodType = Starch.

If I do the below, however, the rowcount will decrement with every delete
and I end up with a "No row at position... " error.

for (int i=0; i <= FoodDataTable.Rows.Count- 1; i++)
{
if (FoodDataTable.Rows(i)("FoodType").ToString() == "Starch"
FoodDataTable.Rows(i).Delete();
}

Can anyone help me around this?

Thanks for any help,
Ron
 
Ronald said:
Consider the following DataTable:

FoodId FoodName FoodType
1 Apple Fruit
2 Pear Fruit
3 Corn Vegetable
4 Bread Starch
5 Cereal Starch
6 Carrot Vegetable
7 Grapes Fruit

I want to delete all records where FoodType = Starch.

If I do the below, however, the rowcount will decrement with every
delete and I end up with a "No row at position... " error.

for (int i=0; i <= FoodDataTable.Rows.Count- 1; i++)
{
if (FoodDataTable.Rows(i)("FoodType").ToString() == "Starch"
FoodDataTable.Rows(i).Delete();
}
foreach (DataRow row in FoodDataTable.Select("FoodType = 'Starch'")) {
row.Delete();
}
 
Back
Top