How to roll back changes in gridview in case of incorrect input
I have a DataGridView that is bound to a list of object. It has开发者_开发技巧 some columns that the user can edit. There are certain inputs that are not allowed for a row as a whole. How can I roll back if the user enters invalid inputs in some cell. I tried using the RowValidating event handler but it was not called after cell value has been changed. Even when I implemet CellValueChanged, I still cannot roll back the changes. ... Any idea how to accomplish this
When databinding exists, for me it works with:
myBindingSource.CancelEdit();
myDataGridView.RefreshEdit();
Once editing has been completed and you validate the changes, you can do this:
DataTable dt = this.dataGridView.DataSource as DataTable;
dt.RejectChanges();
From MSDN:
When the DataTable.RejectChanges method is called, any rows still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state (DataRowState.Unchanged).
You can use the CellValidating event to check the contents of the cell just before it is committed. If you don't like it (whatever your validation rules are), you have a few options.
1) You can Cancel the event. The user gets an error icon on the row, and cannot leave the cell. They are locked into the cell edit behavior until they commit the cell (Enter, Tab) with valid data.
2) You can roll back the value to another value (the 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.
}
}
}
精彩评论