You can use the PreviewKeyDown event to fix a problem with keyboard input on your DataGridView. You have an issue with keyboard navigation. If the user focuses a cell and presses enter, the selection might not work properly. Here we look at how to use this event in Windows Forms and what it does, using the C# programming language.
The first thing the author tried to do was use KeyCode and KeyDown. When the enter key was detected, my dialog would close and the author would see the appropriate response. However, when he went to open the dialog again, the selection would not be in the same place. 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;
}
}Stops selection. That means we stop the KeyDown from moving the selection. However, before the runtime raises the KeyDown event, it will raise the PreviewKeyDown event. Basically, you can combine these events to eliminate the selection problem with it getting out of place.
void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//
// If the key pressed is enter, then call ProceedOpen.
//
if (e.KeyCode == Keys.Enter)
{
ProceedOpen();
}
}Does it really work? Yes, the code shown does fix selection problems. With this technique, the selection stays in the same place, and ProceedOpen is called on the current cell. The user can open the dialog, move with the keyboard to a cell, press enter, and everything works as expected.
Here we looked at the PreviewKeyDown method in the Windows Forms platform using the C# programming language. PreviewKeyDown can help your keyboard navigation techniques work well. This article was written to provide you with a clue about the PreviewKeyDown event and a possible use for it. PreviewKeyDown can solve selection moved problems in Windows Forms. You can find more information about the KeyCode property on this site as well.