The DataGridView is a terrific control built into .NET that provides a customizable table for entering and displaying data. If you provide the DataGridView in your software as a means for the user to enter multiple rows of data, you may wish to redefine the default behavior of the Enter key.

By default, when you press the Enter key in the DataGridView, the cursor moves to the cell in the same column immediately below the current cell (red arrow in the image below). But when entering multiple rows of data, a better response from the Enter key would be to move the cursor to the first cell in the next row (blue arrow).


To do this, you can derive a new class from the DataGridView:

public class Grid : DataGridView

Then override the OnKeyUp protected method as follows:

protected override void OnKeyUp( KeyEventArgs e )
    if (e.KeyCode == Keys.Enter)
        int currentRow = this.CurrentRow.Index;
        if (currentRow >= 0)
            this.CurrentCell = this.Rows[currentRow].Cells[0];
    base.OnKeyUp( e );

Of course, if you wish to provide this capability for an existing DataGridView, you can simply subscribe to the KeyUp event and execute the same code above in the event handler.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot