whytheq
whytheq

Reputation: 35557

Deleting all the data from a datagridview

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();

Upvotes: 0

Views: 15189

Answers (1)

David Hall
David Hall

Reputation: 33143

Fortunately the DataGridView provides a method to do this for us, simply call Clear like so:

uxDGV.Rows.Clear();

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 IsNewRow property on DataGridView rows.

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:

int rowCount = dataGridView1.Rows.Count;
for (int n = 0; n < rowCount; n++)
{
    if (dataGridView1.Rows[0].IsNewRow == false)
        dataGridView1.Rows.RemoveAt(0);
}

Upvotes: 8

Related Questions