DataGridView cell causing validation on simple arrow keys

孤街醉人 提交于 2020-01-06 14:42:49

问题


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?

Note: Examining call stack shows that KeyDownevent triggers a CommitEdit call, which in turn raises OnCellValidating.


回答1:


Like it or not, this is the way things are desigend to work. See MSDN on CellValidating:

Occurs when a cell loses input focus, enabling content validation.

And to make it complete MSDN on CellValidated:

Occurs after the cell has finished validating.

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.



来源:https://stackoverflow.com/questions/27263912/datagridview-cell-causing-validation-on-simple-arrow-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!