I have written a code in row_validating event which works fine.
now I want to clear this rows containing error in cells of datagridview.
I tried this code.

private void grdvEnergy_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
     e.Cancel = true;
     datagridview1.Rows[e.RowIndex].ErrorText = "Error message";
}

 private void btnclear_Click(object sender, EventArgs e)
{
    datagridview1.Rows.Clear();
}

But it gives me this error:

"Operation did not succeed because the program cannot commit or quit a cell value change."

You are canceling the row validation for all rows, including valid ones.

private void grdvEnergy_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
     e.Cancel = true; //<-- this should only be done if an error exists.
     datagridview1.Rows[e.RowIndex].ErrorText = "Error message";
}

You need to add a conditional statement to allow valid rows to commit.

private void grdvEnergy_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
    if(!<valid condition>) // test if not valid
    {
        e.Cancel = true;
        datagridview1.Rows[e.RowIndex].ErrorText = "Error message";
    }
}

datagridview1.Rows.Clear(); will remove all rows from your data grid.
Is this what you want to do?

If you only want to remove the current row then use this.

dataGridView1.Rows.Remove(dataGridView1.CurrentRow);

Also, setting e.Cancel = true; in the row validating method prevents focus from moving to any other control.
If you are setting the ErrorText, then you probably do not need to set Cancel. Think about removing it.

commented: Nice! +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.