I don\'t understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
<
Sure Magents
This is how I did it and works fine
dt = GetStationeryConsolidationDetails(txtRefNo.Text);
int intRows = dt.Rows.Count;
int x = 0;
for (int c = 0; c < intRows; c++)
{
if (dt.Rows[c - x]["DQTY"].ToString() == "0")
{
dt.Rows[c - x].Delete();
dt.AcceptChanges();
x++;
}
}
If you call the delete method you just have to call AcceptChanges()
on the table you are modifying, after the foreach loop.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
dataTable.AcceptChanges();
The delete method simply marks the row for deletion.
http://msdn.microsoft.com/en-us/library/system.data.datarow.delete%28v=VS.90%29.aspx
The Rows
content changes while you are iterating if you delete one row, which renders the iteration invalid.
You can, however, copy the rows into a collection first and then iterate over the collection and delete the rows that way. This makes sure that the iteration is not interrupted by changing data to be iterated.
Use this:
for (int i = 0; i < myDataTable.Rows.Count; i++)
{
myDataTable[i].Delete();
}
Where items have a Count
, this is what I have done:
int Count = myTable.Rows.Count;
while (Count > 0) // replace condition with myTable.Rows.Count if unconditionally performed on all rows
{
DataRow row = myTable.Rows[0] // or however you want to find your index
// do some work
myTable.Rows.Remove(row);
// if you want to perform a check to break out of while
if (someCondition)
Count = 0;
else
Count = myTable.Rows.Count;
}
Note, that where objects have a .GetXXXX()
collection, like FileInfo
(IIRC),
deleting item contents in a foreach
is acceptable. One solution I have considered is creating an extension method that provides a .GetItems()
method.
This is because it looks like try to disassemble the stair of staircase that you climb. Simply, you cannot remove an item you iterate.
Therefore you should use different array to iterate and remove them from datatable Rows
property.
foreach (DataRow dataRow in dataTable.Select())
{
if (true)
{
dataTable.Rows.Remove(dataRow);
}
}