Kwe*_*ell 2 c# datagridview winforms
我的目标是在DataGridView上建立友好的验证流程。
当用户为某个单元格输入不正确的值时,我想要:
我目前正在使用CellValidating事件来防止单元格更新其值,但是我无法退出编辑模式。然后该单元格正在等待正确的值,不会让用户简单地取消并还原其操作...
验证方法如下所示:
private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
[...] // Here, treatment determines is the new cell value isValid or not
if (!isValid)
{
MessageBox.Show("The value entered is incorrect.", "Modification aborted");
e.Cancel = true;
dataGridViewMsg[e.ColumnIndex, e.RowIndex].IsInEditMode = false; // Someway, what I would like to do
return;
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不要求我跟踪此值的情况下使单元恢复其原始值?
您可以EndEdit()用来获取想要的东西。
无论如何,请注意最好确保取消仅在预期条件下发生;否则,代码可能会卡在此事件中,因为它会在许多不同的点被自动调用。例如,要验证用户通过单元格版本编写的输入,您可以依靠以下方法中的一种方法:
bool cancelIt = false;
private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
[...] // Here, treatment determines is the new cell value isValid or not
if (cancelIt && !isValid)
{
MessageBox.Show("The value entered is incorrect.", "Modification aborted");
e.Cancel = true;
dataGridViewMsg.EndEdit();
cancelIt = false;
}
}
//CellBeginEdit event -> the user has edited the cell and the cancellation part
//can be executed without any problem
private void dataGridViewMsg_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
cancelIt = true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6260 次 |
| 最近记录: |