0

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."

2
Contributors
2
Replies
6
Views
7 Years
Discussion Span
Last Post by nick.crane
1

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";
    }
}
1

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.

Edited by nick.crane: n/a

Votes + Comments
Nice!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.