I am presenting a form as a dialog box. The form contains a DataGridView, a TextBox and OK/Cancel buttons, as follows:
If the textbox has focus, then pressing Enter closes the form with a DialogResult of OK. However, if the DataGridView has focus then pressing Enter does not close the form.
Pressing the Escape key, however, always results in the form closing with a DialogResult of Cancel.
This is a two part question:
The DataGridView
uses the enter key to move to the cell below the cell currently being edited. There is no single property to change this behaviour, but you can override the keydown behaviour of the grid:
dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown);
void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1.PerformClick();
e.Handled = true;
}
}
This still leaves you with arrow keys for navigation and still allows users to add new rows (the new row appears as soon as data is entered in the bottom row of the grid).
I imagine that enter is a valid key for data-entry, along with tab, and one that they want to preserve for those users who are most used to the keyboard, as opposed to point and click.
Have you tried adding a call to PerformClick(), perhaps within your key-down event handler?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With