Home
C#.WinForms
PreviewKeyDown Event
Updated Sep 26, 2022
Dot Net Perls
PreviewKeyDown. This fixes a problem with keyboard input on DataGridView. If the user focuses a cell and presses enter, the selection might not work properly.
By using PreviewKeyDown, we can correct an issue with keyboard navigation. If you have a problem with selecting moving, consider PreviewKeyDown.
Example. Let us closely examine the problem using KeyCode and KeyDown. When the enter key was detected, my dialog would close and I would see the appropriate response.
However When I went to open the dialog again, the selection would not be in the same place.
Tip We can combine PreviewKeyDown and KeyDown. Take KeyDown, and set its event Handled property to true.
void dataGridView1_KeyDown(object sender, KeyEventArgs e) { // // Set the key down event has handled. // We call our function ProceedOpen in the PreviewKeyDown event instead. // if (e.KeyCode == Keys.Enter) { e.Handled = true; } }
PreviewKeyDown example. Here we stop the KeyDown from moving the selection. However, before the runtime raises the KeyDown event, it will raise PreviewKeyDown.
And You can combine these events to eliminate the selection problem with it getting out of place.
Tip The code fixes selection problems. The selection stays in the same place, and ProceedOpen is called on the current cell.
Thus The user can open the dialog, move with the keyboard to a cell, press enter, and everything works as expected.
void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { // // If the key pressed is enter, then call ProceedOpen. // if (e.KeyCode == Keys.Enter) { ProceedOpen(); } }
A summary. PreviewKeyDown can help your keyboard navigation techniques work well. PreviewKeyDown can solve selection moved problems in Windows Forms.
KeyCode
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen