Reputation: 23
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
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