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

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
 
P

Peter Morris

for (int i = FoodDataTable.Rows.Count - 1; i >= 0; i--)



--
Pete
=========================================
I use Enterprise Core Objects (Domain driven design)
http://www.capableobjects.com/
=========================================
 
J

Jeroen Mostert

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();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top