Deleting rows in ADO.NET

  • Thread starter Thread starter Dmitry Karneyev
  • Start date Start date
D

Dmitry Karneyev

Hi!

I try to delete rows from the table in such way
foreach(DataRow row in MyDataSet.MyTable)
{
row.Delete();
}
and recive an error that collection is changed and enumeration is
impossible.
I guesss that foraech operator uses collection of undeleted rows and this
causes such behaviour.

Is there another approach to mark all rows in the table to deleted state?

Thanks
Dmitry
 
accurate code is:

foreach(DataRow row in MyDataSet.MyTable.Rows)
{
row.Delete();
}

Dmitry
 
Dmitry,

The easier way would be to cycle through the rows backwards (using an
index), and then call the delete method on them while you cycle backwards,
like this:

// Cycle backwards.
for (int pintIndex = MyDataSet["MyTable"].Rows.Count - 1; pintIndex >= 0;
pintIndex--)
// Delete the row.
MyDataSet["MyTable"].Rows[pintIndex].Delete();

Hope this helps.
 
Hi Nicholas,

Actualy your way would be the only correct.
The reason is that if row is in Added RowState and you call Delete() on it,
it will be *removed* from collection and cause an exception if you are
within foreach loop like Dmitry does or index out of range if within
positive for loop.

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

Nicholas Paldino said:
Dmitry,

The easier way would be to cycle through the rows backwards (using an
index), and then call the delete method on them while you cycle backwards,
like this:

// Cycle backwards.
for (int pintIndex = MyDataSet["MyTable"].Rows.Count - 1; pintIndex >= 0;
pintIndex--)
// Delete the row.
MyDataSet["MyTable"].Rows[pintIndex].Delete();

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Dmitry Karneyev said:
Hi!

I try to delete rows from the table in such way
foreach(DataRow row in MyDataSet.MyTable)
{
row.Delete();
}
and recive an error that collection is changed and enumeration is
impossible.
I guesss that foraech operator uses collection of undeleted rows and this
causes such behaviour.

Is there another approach to mark all rows in the table to deleted state?

Thanks
Dmitry
 
What about this?

while (myTable.Rows.Count > 0)
{
myTable.Rows[0].Delete();
}

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Frank,

That should work fine as well. The only problem with this is that you
have to be sure that the Count property is affected by the Delete, and not
just set so that the row is in a "delete" state.
 
Back
Top