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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).