Dot Net Perls
C#

PreviewKeyDown on DataGridView

by Sam Allen

Problem

Use PreviewKeyDown event to fix a problem with keyboard input on your DataGridView. Our DataGridView might an issue with keyboard navigation. If the user focuses a cell and presses enter, the selection might not work properly and would go down. You need the dialog to be accepted and close.

Solution: C#

The first thing I tried to do was use 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.

PreviewKeyDown. We can combine PreviewKeyDown and KeyDown. There are other ways to accomplish this goal, but this way works well and was reliable in my testing. Let's get started. 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();
    }
}

Discussion

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 a selection moved problem in Windows Forms.

Does it really work?

Yes. 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. Later the selection is in the same place.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge