DataGridView control and the Enter key.
Because of the type of data processing applications I develop, I try to design them in such a fashion that the mouse is largely unnecessary. This means a lot of function keys, hidden context menus, tab order, and Focus() manipulation. For the most part, with just a little forethought and effort, you can make an app very responsive to a “heads down” data processor.
Here is one example I ran in to today while working on a fairly typical database management type utility. The user performs a database search and is presented with a list of records that match the query. These records are listed in a DataGridView control and immediately after the search is complete, Focus() is transferred to the DataGridView control. Now the user can easily use the Up and Down arrow keys to navigate the Grid, but record selection becomes a little tricky.
Intuitively, the user should be able to highlight the desired record and press the Enter key on the keyboard to select the record. Unfortunately, the default behavior of the DataGridView control does not function this way: when the Grid has the focus, pressing the Enter key will advance the highlighted cell to the one immediately below it, just like pressing the down arrow key. This is not intuitive and in my case is down right unacceptable.
To bypass this behavior, we need to monitor the KeyDown event, and if the Enter key has been pressed, instruct the Grid control to ignore its default behavior. We do so by setting the KeyEventArgs Handled property to true:
{
if (e.KeyData == Keys.Enter)
{
e.Handled = true;
}
}
Now the highlighted cell will not change when the Enter key is pressed. Then in the KeyUp event, we can instruct the Grid to perform whatever task we wish to process the record:
{
if (e.KeyData == Keys.Enter)
{
this.RecordSelected();
}
}
And now we have a DataGridView control that handles the Enter key in a more intuitive fashion.
if (YouLikeIt) {
3 Comments so far
Leave a reply
Nice tip, but i encountered a little problem, yet when i edit the cell and press enter button the focus goes down(cell down).
That was the original problem I had, and the above code was the solution. Could you post some of what you have for comparison? Also, this was written for 2.0: what version are you coding in?
Very nice. This is exactly what I was looking for — it works! Joel, thank you.