Skip to main content

Default behaviour when the Enter key is pressed in DataGridView is to select the next row. Many times a customer would like to have some other behaviour, e.g. Enter to edit the current row or to open a window with detailed information.

- Advertisement -
- Advertisement -

In this article we'll demonstrate how to change default Enter key pressed in DataGridView. This example will show a simple message box displaying string value in the first cell of selected row. You can change it with your logic, just copy the method into the form where your datagridview is located (we assume that the datagridview is named dataGridView1).

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // Check if Enter is pressed
    if (keyData == Keys.Enter)
    {
        // If there isn't any selected row, do nothing
        if (dataGridView1.CurrentRow == null)
        {
            return true;
        }
        
        // Display first cell's value
        MessageBox.Show(dataGridView1.CurrentRow.Cells[0].Value);
        
        return true;
    }
 
    return base.ProcessCmdKey(ref msg, keyData);
}

- Advertisement -