How to undo changes in gridview in case of incorrect input

I have a DataGridView tied to a list of objects. It has several columns that the user can edit. There are certain inputs that are not allowed for the string as a whole. How can I roll back if the user enters invalid inputs in any cell. I tried using the RowValidating event handler, but it was not called after changing the cell value. Even when I implement CellValueChanged, I still cannot undo the changes. ... any idea how to do this

+5
source share
3 answers

When data binding exists, for me it works with:

myBindingSource.CancelEdit();
myDataGridView.RefreshEdit();
+10

:

DataTable dt = this.dataGridView.DataSource as DataTable;
dt.RejectChanges();

MSDN:

DataTable.RejectChanges , , edit-mode . . (DataRowState.Unchanged).

+5

CellValidating, . ( ), .

1) You can cancel the event. The user receives an error icon in the row and cannot leave the cell. They are locked in cell editing mode until they lock the cell (Enter, Tab) with valid data.

2) You can drop the value to another value (previous value, some default value).

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    DataGridView grid = sender as DataGridView;
    if (grid.Columns[e.ColumnIndex].HeaderText == "Text ID")
    {
        // Suppose you want to prevent them from leaving a cell when the text
        // in a specific column contains spaces:

        // value will hold the new data
        string value = (string)e.FormattedValue;

        if (value.Contains(" "))
        {
            grid.Rows[e.RowIndex].ErrorText = "String IDs cannot contain spaces.";
            // Setting e.Cancel will prevent them from leaving the cell.
            e.Cancel = true;
        }
    }
    else if (grid.Columns[e.ColumnIndex].HeaderText == "Platform")
    {
        // Or, suppose you have another column that can only contain certain values.
        // You could have used a ComboBoxColumn, but it didn't play with paste, or something.
        if (grid.EditingControl != null && (string)e.FormattedValue != "All")
        {
            // Going straight to the EditingControl will allow you to overwrite what
            // the user thought they were going to do.

            // Note: You don't want to e.Cancel here, because it will lock them
            // into the cell. This is just a brute force fix by you.
            string oldvalue = (string)grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            grid.EditingControl.Text = "All"; // or set it to the previous value, if you like.
        }
    }
}
0
source

All Articles