Displaying data directly from the data sources with a readable format readable is one of the benefits of using a grid view among others. Its quick implementation and easy connection to data sources makes it an ideal solution for beginner programmers. But my honeymoon with
DataGridView ended when I advanced its purpose to entering data.
Since it look and feel is ideal for entering data, I attempted to use it to enter data using the cells for each item of data. When, what, and which event is triggered? All these things got me confused. Well, it took me quite a while, but I finally got the hang of it, but one of the things I could not go around was its behavior of vertical focus movement.
Once a user enters a data in to a cell and presses “Enter”, the focus goes to the next cell in the same column, vertically. In my case, in most of the situations, I wanted to enter data in a single row, one cell at a time. So driven by the fuel of looking for a solution, I wrote a very small code that will perform this task.
Using the code
I tried most of the possibilities to handle the key and focus events of the current cell to perform this task, they ended up wasting my time and frustrating me. Finally, I decided to override the functions that process
DataGridView keys. In order for me to override these methods and for this component to be used any time, I extended the normal
DataGridView using the code, to create a custom control.
public class DataGridViewEx : DataGridView
The other thing about the grid view is, the focus moves with the navigation keys (Left, Right, Up, Down). What I did was override this behavior to make it think that the user has pressed the navigation keys whenever I wanted, and that is the basis of this solution. As in the code shown, override "
ProcessDialogKey" and whenever the user presses Enter, call the method that moves the focus to the next cell.
protected override bool ProcessDialogKey(Keys keyData)
if (keyData == Keys.Enter)
The code for the move to the next cell goes like this:
public void MoveToNextCell()
int CurrentColumn, CurrentRow;
CurrentColumn = this.CurrentCell.ColumnIndex;
CurrentRow = this.CurrentCell.RowIndex;
if (CurrentColumn == this.Columns.Count - 1 &&
CurrentRow != this.Rows.Count - 1)
Moving to the next cell means pressing the "right" key so that is what this code makes the
DataGridView think. Furthermore, I have added code so that when the user reaches the end of the grid, the focus goes to the first cell of the next row, simulated by the keys "Home", then "Down", because that is what you basically do if you wish to move to the next cell in line.
To use this control, all that is needed to be done is to download the assembly from this article and reference it. You will find the control in the toolbox. Since the rest of the properties of this control are same as that of the
DataGridView, it will be easier to work with.