问题描述
DataGridView 为什么通过箭头键简单的导航来增加 CellValidating
事件?我该怎么防止呢?以下是关于 DataGridView
的状态,当它调用 CellValidating
时:
Why does DataGridView
raise CellValidating
event upon simple navigation through arrow keys? How can I prevent it? Here is the key information about DataGridView
state when it calls CellValidating
:
EditMode = EditOnKeyStrokeOrF2
IsCurrentCellInEditMode = False
e.FormattedValue = [Same as the current value of the cell]
如您所见,用户没有触发任何编辑操作。他只是按着右箭头键移动通过单元格。一个人不会期望在这一点上发生验证,对吗?
As you can see, user has not triggered any editing operation. He's just moving across the cells by pressing right-arrow key. One would not expect validation to occur at this point, right?
注意:检查调用堆栈显示 KeyDown
事件触发一个 CommitEdit
调用,这又调用 OnCellValidating
。
Note: Examining call stack shows that KeyDown
event triggers a CommitEdit
call, which in turn raises OnCellValidating
.
推荐答案
喜欢与否,这是事情想要工作的方式。请参阅 on CellValidating
:
Like it or not, this is the way things are desigend to work. See MSDN on CellValidating
:
并使其完成在 CellValidated
:
最直接和可读的解决方案可能是在$ code> CellValidating 事件开始时放置一个这样的行:
The most direct and readable solution is probably to put a line like this at the start of the CellValidating
event:
if (!dataGridView1.IsCurrentCellDirty) return;
设计行为的一个原因可能是实际需要用户输入创建有效的单元格值。不是你的情况,但仍然是一个可以想象的要求。
One reason for the designed behaviour could be the case where a user input is actually needed to create a valid cell value. Not your case, but still a conceivable requirement.
这篇关于DataGridView单元格导致对简单箭头键的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!