编辑时回滚datagridview的旧值

And*_*ana 3 c# datagridview winforms

我有一个datagridview1. 当用户编辑单元格值时,我想检查数据的验证。如果无效,则将单元格值回滚到旧值。

CellValidating事件中,我使用了:

e.Cancel = true;
Run Code Online (Sandbox Code Playgroud)

但价值没有回滚我该怎么做?

OhB*_*ise 7

设置e.Cancel = true只是取消退出编辑,强制用户编辑当前单元格,直到它有效。相反,允许进行编辑,但将值重置为原始值。将您发布的代码行替换为以下内容:

dataGridView1.EditingControl.Text = dataGridView1.CurrentCell.Value.ToString();
Run Code Online (Sandbox Code Playgroud)

编辑:或者只是用下面的代码行替换上面的。这具有不丢失数据类型并取消添加NewRowif 的进一步优点。

this.dataGridView1.CancelEdit();
Run Code Online (Sandbox Code Playgroud)

  • +1,谢谢。使用 CancelEdit() 的唯一缺点是单元格在编辑模式下保持选中状态。我更喜欢使用恢复(您的第一个答案)并继续执行 **dataGridView.EndEdit()**。在这种情况下,将恢复网格单元格标记,而不是编辑模式光标。 (2认同)