The following function is implemented to to remove all selected rows if met the condition from UltraGrid and from database:
private void RemoveRows()
{
foreach (var row in dgvReceords.Selected.Rows)
{
var order = row.Cells["Order"].Value;
if (order== null || string.IsNullOrEmpty(order.ToString().Trim()))
{
// Update database via business object and then update grid
OrderBO.DeleteByPrimaryKey(row.Cells["Id"].Text);
if (OrderBO.Save() == SaveResult.Success)
row.Delete();
}
}
}
The problem it fails to iterate through all rows and always leave one row behind. Any idea what is wrong here?
This is because the foreach()
uses collection that the .Delete()
are modifying. Try to use for()
and remove in reverse order:
private void RemoveRows()
{
for (var i=dgvReceords.Selected.Rows.Count-1; i >= 0; i--)
{
var row = dgvReceords.Selected.Rows[i];
var order = row.Cells["Order"].Value;
if (order== null || string.IsNullOrEmpty(order.ToString().Trim()))
{
// Update database via business object and then update grid
OrderBO.DeleteByPrimaryKey(row.Cells["Id"].Text);
if (OrderBO.Save() == SaveResult.Success)
dgvReceords.Selected.Rows[i].Delete();
}
}
}