Robert Heeren
Robert Heeren

Reputation: 23

Error using .RemoveAt to delete a DataTable row in a loop

I'm working on a program and don't know how to fix this problem i'm having now.

When i run this code:

int maxRows = AfdelingDT.Rows.Count;
maxRows -= 1;
for(int i = 0;i <= maxRows; i++)
{
   if (Convert.ToInt16(AfdelingDT.Rows[i][0]) == Convert.ToInt16(removeRowTB.Text))
   {
      AfdelingDT.Rows.RemoveAt(i);
   }
}

I'm having a error that the row doesn't exist if I try to delete a row in the middle of the DataTable.

If I run the code for the last row of the table I have no problem at all.

Upvotes: 1

Views: 1898

Answers (1)

C-Pound Guru
C-Pound Guru

Reputation: 16368

The problem is that when you remove a row inside a loop, it renumbers all the rows after that point, causing breakage.

Change your code to loop from the end to the beginning:

int maxRows = AfdelingDT.Rows.Count;
maxRows -= 1;
for(int i = maxRows;i >= 0; i--)
{
   if (Convert.ToInt16(AfdelingDT.Rows[i][0]) == Convert.ToInt16(removeRowTB.Text))
   {
      AfdelingDT.Rows.RemoveAt(i);
   }
}

Upvotes: 1

Related Questions