Don*_*kby 9 c# datagridview winforms
我在WinForms应用程序中使用DataGridView.我的主要目标是使Enter键不移动到网格中的下一行.我仍然希望输入键验证并结束编辑模式.
我发现这个FAQ条目和子类DataGridView重写ProcessDialogKey().如果按下的键是Enter,我调用EndEdit(),否则我调用base.ProcessDialogKey().
它工作得很好,除了没有触发CellValidating事件.
目前,我只是在调用EndEdit之前手动调用我的验证逻辑,但似乎我错过了一些东西.
我想我可以打电话给OnCellValidating,但后来我担心我错过了其他一些事件.我真正想要的是一些EndEdit()的行为,就像在添加禁用的网格的最后一行按Enter一样.
JJO*_*JJO 11
在更改CurrentCell之前,不会调用CellValidating.所以我解决这个问题的方法是更改CurrentCell,然后切换回当前的.
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
DataGridViewCell currentCell = CurrentCell;
EndEdit();
CurrentCell = null;
CurrentCell = currentCell;
return true;
}
return base.ProcessDialogKey(keyData);
}
Run Code Online (Sandbox Code Playgroud)
如果单元格处于编辑模式,JJO的代码将崩溃.以下避免了验证异常:
DataGridViewCell currentCell = AttachedGrid.CurrentCell;
try
{
AttachedGrid.EndEdit();
AttachedGrid.CurrentCell = null;
AttachedGrid.CurrentCell = currentCell;
}
catch
{
AttachedGrid.CurrentCell = currentCell;
AttachedGrid.CurrentCell.Selected = true;
}
Run Code Online (Sandbox Code Playgroud)
资料来源:Kennet Harris的回答
| 归档时间: |
|
| 查看次数: |
23998 次 |
| 最近记录: |