如果输入不正确,如何回滚gridview中的更改

时间:2010-03-17 06:35:23

标签: c# winforms datagridview error-handling

我有一个绑定到对象列表的DataGridView。它有一些用户可以编辑的列。某些输入不允许作为一个整体的行。如果用户在某个单元格中输入无效输入,我该如何回滚。 我尝试使用RowValidating事件处理程序,但在更改单元格值后未调用它。即使我实现CellValueChanged,我仍然无法回滚更改。 ... 知道如何完成这个

3 个答案:

答案 0 :(得分:11)

当存在数据绑定时,对我来说它适用于:

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

答案 1 :(得分:5)

完成编辑并验证更改后,您可以执行以下操作:

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

来自MSDN

  

当DataTable.RejectChanges时   调用方法,任何行仍在   编辑模式取消他们的编辑。新行   被删除。修改和删除的行   回到原来的状态   (DataRowState.Unchanged)。

答案 2 :(得分:0)

您可以使用CellValidating事件在提交之前检查单元格的内容。如果您不喜欢它(无论您的验证规则是什么),您都有一些选择。

1)您可以取消活动。用户在行上获得错误图标,并且无法离开单元格。它们被锁定在单元格编辑行为中,直到它们使用有效数据提交单元格(Enter,Tab)。

2)您可以将值回滚到另一个值(前一个值,一些默认值)。

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