DataGridView "Enter" key event handling

40,472

Solution 1

That's the default behaviour of the DataGridView, and pretty standard in other data grids by 3rd party vendors too.

Here is what happens:

  1. The user hits the enter key
  2. The DataGridView receives the KeyPress event and performs various actions (such as ending edits, etc), and then moves the cell down one row.
  3. Then the DataGridView checks to see if there are any event handlers hooked up by you and fires those.

So by the time the enter key is pressed, the current cell has already changed.

You could use the following if you want to get the row that the user was on before the DataGridView changes the row. This should fit in with your existing code (obviously you will need to add the event handler for it):

void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        int i = dataGridView1.CurrentRow.Index;
        MessageBox.Show(i.ToString());
    }     
}

I hope that helps point you in the right direction. Not sure what you are hoping to do here, but hopefully this explains what you are seeing happen.

Solution 2

Add a Class with the following code and modify your GridView designer page i.e.,

this.dataGridView1 = New System.Windows.Forms.DataGridView();

to

this.dataGridView1 = new GridSample_WinForms.customDataGridView();

the class file is:

class customDataGridView : DataGridView
{
  protected override bool ProcessDialogKey(Keys keyData)
  {
     if (keyData == Keys.Enter)
     {
        int col = this.CurrentCell.ColumnIndex;
        int row = this.CurrentCell.RowIndex;
        this.CurrentCell = this[col, row];
        return true;
     }
     return base.ProcessDialogKey(keyData);
  }

  protected override void OnKeyDown(KeyEventArgs e)
  {
     if (e.KeyData == Keys.Enter)
     {
        int col = this.CurrentCell.ColumnIndex;
        int row = this.CurrentCell.RowIndex;
        this.CurrentCell = this[col, row];
        e.Handled = true;
     }
     base.OnKeyDown(e);
  }
}

Solution 3

The following solution is simpler and also works:

  1. In the .Designer.cs file:

    this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView1_KeyDown);

  2. In the code behind file:

     private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
     {
         if (e.KeyData == Keys.Enter)
         {
             // Handle event
             e.Handled = true;
         }
     }
    
Share:
40,472
MSanika
Author by

MSanika

Passionate Software Developer

Updated on July 09, 2022

Comments

  • MSanika
    MSanika almost 2 years

    I have a DataGridView populated with DataTable, have 10 columns. I have a scenario when moving from one row to another when I click on Enter key then I need that row should be selected and need to have that row values.

    But here when I select n-th row then it automatically moves to n+1 Row.

    Please help me in this...

    In Page Load Event:

    SqlConnection con = 
        new SqlConnection("Data Source=.;Initial Catalog=MHS;User ID=mhs_mt;Password=@mhsinc");
    
    DataSet ds = new System.Data.DataSet();
    SqlDataAdapter da = new SqlDataAdapter("select * from MT_INVENTORY_COUNT", con);
    da.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
    

    Then,

    private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (e.KeyChar == (Char)Keys.Enter)
         {
               int i = dataGridView1.CurrentRow.Index;
               MessageBox.Show(i.ToString());
         }     
    }
    
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int i = dataGridView1.CurrentRow.Index;
        MessageBox.Show(i.ToString());
    }
    
  • MSanika
    MSanika about 10 years
    I am getting wrong as I expected , CurrentRow index automatically increments with 1 but not this same with GridView's last row. any help ?
  • Adam Valpied
    Adam Valpied about 10 years
    If you hook up the PreviewKeyDown event, it will fire before the DataGridView moves the cell down a row. For example, I ran your code with my suggestion and got two message boxes. One said "2" - as it was on the 3rd row, and the next - from the KeyPress event said "3" - as it moved down to the next row before that handler was called. Is that not what you experience?
  • Adam Valpied
    Adam Valpied about 10 years
    I should mention that if you are editing a cell the PreviewKeyDown event will not fire when the Enter key is pressed, but neither will the KeyPress event. That's because the text box that being used to edit the data in the DataGridView handles the keyboard input. You can attach a handler to that too, but it's a bit more work. Let me know if you would like me to show you how.
  • MSanika
    MSanika about 10 years
    In my scenario when I press 'Enter' key then that row should be selected and need to capture those values.
  • Adam Valpied
    Adam Valpied about 10 years
    Not sure what you are trying to accomplish. Is anything in this post of help: link?
  • rosta
    rosta about 9 years
    Thanks, I was looking for this. ProcessDialogKey is the way how to capture KeyDown if I am in a Cell
  • xvan
    xvan over 2 years
    This should be the accepted answer