Why doesn’t this work?
//::::::::::::::::::::::::::::::::::::
private void uxClearButton_Click(object sender, EventArgs e)
{
clearDGV();
}
void clearDGV()
{
// remove selected rows
foreach (DataGridViewRow row in uxDGV.Rows)
{
uxDGV.Rows.Remove(row);
}
}
//:::::::::::::::::::::::::::::::::::
The DGV is not bound and the user has typed information into it.
Error I get is InvalidOperationException was unhandled Uncommitted new row cannot be deleted.
EDIT
ok – thanks to Steve etc for encouraging me to find the answer for myself!!
uxChargeBackDataGridView.Rows.Clear();
Fortunately the
DataGridViewprovides a method to do this for us, simply callClearlike so:The reason you were getting your error was because you were trying to remove the uncommitted new row. (the error is actually nice and informative once you know the problem!)
The new row is identified by the boolean
IsNewRowproperty onDataGridViewrows.In your code you also had the problem of iterating over a collection as you modify it. So you would have needed to do something like below, where we iterate forwards but remove at zero each time: