Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get "Accept" button to fire when DataGridView has focus?

I am presenting a form as a dialog box. The form contains a DataGridView, a TextBox and OK/Cancel buttons, as follows:

enter image description here

  • I have set the AcceptButton property of the form to the OK button and the CancelButton property of the form to the Cancel button.
  • I have set the DialogResult property of the OK button to "OK" and the DialogResult property of the Cancel button to "Cancel"

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:

  1. What is the reason for the inconsistent behaviour of the Enter key when the DataGridView has focus?
  2. How can I cause Enter to close the form with a DialogResult of OK when the DataGridView has focus?
like image 692
Warren Blumenow Avatar asked Dec 12 '22 04:12

Warren Blumenow


2 Answers

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).

like image 119
David Hall Avatar answered May 10 '23 01:05

David Hall


  1. 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.

  2. Have you tried adding a call to PerformClick(), perhaps within your key-down event handler?

like image 40
dwerner Avatar answered May 10 '23 01:05

dwerner