RSS

How to use “Enter” key as “Tab” key in DataGridView ??

26 Jun

This topic is haunting developers. Developer always wants to when the user presses the “Enter” or “Return” key the focus moves from the current cell to the next or the next column in a horizontal direction.
Some solutions have been deployed on the Internet using SendKeys.Send method, but the best is the following:

You have a DataGridView control on the form named “dgv“, in the event named “KeyDown” you want to tell your app that if the user pressed the “Return” key moves to the current cell; and if the user is in the last cell of the current row, add a new row and moves to the next cell of it.

Notice, the DataGridView prevents the user from adding new row manually (dgv.AllowUserToAddRows = false;), he have to reach to the last cell and press “Enter” key.

private void dgv_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress = true;
        int iColumn = dgv.CurrentCell.ColumnIndex;
        int iRow = dgv.CurrentCell.RowIndex;
        if (iColumn == dgv.Columns.Count - 1)
        {
            if (dgv.CurrentRow.Index == dgv.Rows.Count - 2)
            {
                dgv.Rows.Add();
                dgv.CurrentCell = dgv[0, iRow + 1];
            }
        }
        else
        {
            dgv.CurrentCell = dgv[iColumn + 1, iRow];
        }
    }
}
 
Leave a comment

Posted by on June 26, 2012 in Visual C# . NET

 

Tags: , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: