C# – Change Default “Enter” Key Behavior In DataGridView to left to right


As we know DataGridView in C# act quite differently with Enter key. When user pressed the Enter key it will take them to next row instead of next column.  For more convenient data entry require left to right movement not top to bottom . C#.Net has ability to change the default behavior of the enter key.

This can be done with overriding the processcmdKey method.

This will change Enter key behavior on the form itself. If you have any code to move focus to other controls it may fail

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)

{

// Check if Enter is pressed

if (keyData == Keys.Enter)

{

try

{

if (dataGridView1.CurrentCell.ColumnIndex == 9)

{

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index + 1].Cells[1];

return true;

}

else

{

SendKeys.Send(“{right }”);

}

}

catch (Exception e)

{

dataGridView1.Rows.Add();

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index ].Cells[1];

 

}

return true;

}

return base.ProcessCmdKey(ref msg, keyData);

}

add the above overriding section to the end of the class methods. The Catch method check for the error when there are no rows and add a new row, focus the column.

The original post which help me to solve the problem can be found on inforbiro.com

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.