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 KeyDown
event triggers a CommitEdit
call, which in turn raises OnCellValidating
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.