Search code examples
c#winformsdatagridviewuser-controls

Preventing Windows Forms DataGridView moving to next row on pressing ENTER key


I know this question (or variants of it) has come up a few times. But So far I have not found a solution that works for me.

I'm writing a Windows Forms UserControl using C# containing a DataGridView to present a read-only collection of employee data as a kind of glorified select list. The grid is read-only (populated on control_load) and has FullRowSelect set as the selection method. I want the user to be able either double mouse click or use the Enter Key on the current row to select an Id value form that row which gets picked up by subscribers to handle elsewhere.

In handling the KeyDown event after assigning my selected employee value, I attempt to prevent selection moving to the next row. This works fine except when the CurrentCell.RowIndex is zero. Does anyone know how I can get this working for CurrentCell.Rowindex = 0 ?

private void dgvEmployees_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (dgvEmployees.CurrentRow.Cells[0].Value != null)
        {
            this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value;
            this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() { 
            SelectedEmployeeId = this.SelectedEmployeeId, 
            SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString() 
            });
        }

        // Prevent pressing <enter key> moving onto the next row.
        if (dgvEmployees.CurrentCell.RowIndex > 0)
        { 
            dgvEmployees.CurrentCell = dgvEmployees[1, dgvEmployees.CurrentCell.RowIndex - 1];
            dgvEmployees.CurrentRow.Selected = true;
        } 
        else
        {
            dgvEmployees.CurrentCell = dgvEmployees[1, 0];
            dgvEmployees.Rows[0].Cells[1].Selected = true;
        }           
    }
}

Solution

  • Thanks to Reniuz fo the heads up. All I needed was either to set e.Handled = true or e.SuppressKeyPress = true replacing the if (dgvEmployees.CurrentCell.RowIndex > 0) statement in it's entirety.

    if (e.KeyCode == Keys.Enter)
    {
        if (dgvEmployees.CurrentRow.Cells[0].Value != null)
        {
            this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value;
            this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() { 
                SelectedEmployeeId = this.SelectedEmployeeId, 
                SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString() 
            });
        }
    
        e.SuppressKeyPress = true;
    }