Hi friends.
I have a datagridview in my project.I want to navigate between cells( in a row) by pressing "Enter".I mean when user edits a cell, navigates to next cell by pressing Enter.(as we know navigation to the next row by pressing enter is the default action)
I tried to change the "currentcell" in datagridview_keypress.but it doesn't work. what should I do?
thx for ur attention.

NoBody can't answer me??!!!!!!!!:(

Here is an extension method to handle moving to the next cell. It doesn't behave exactly like the dataGridView because Microsoft did not expose a method to readily handle processing keys it seems. You could do better emulation if you wanted to use SendKeys() and send a Tab I suppose, but that would be even worse yet I think. You could also create a descendant of the grid...

Anyway this should answer your question for the most part.

Moving to the next cell:

public static class GridExtension
  {
    public static void MoveNextCell(this DataGridView dgv)
    {
      DataGridViewCell currentCell = dgv.CurrentCell;
      if (currentCell != null)
      {
        int nextRow = currentCell.RowIndex;
        int nextCol = currentCell.ColumnIndex + 1;
        if (nextCol >= dgv.ColumnCount)
        {
          nextCol = 0;
          nextRow++;
        }
        if (nextRow >= dgv.RowCount)
        {
          nextRow = 0;
        }
        DataGridViewCell nextCell = dgv.Rows[nextRow].Cells[nextCol];
        if (nextCell != null && nextCell.Visible)
        {
          if ((currentCell != null) && (currentCell.IsInEditMode))
            dgv.EndEdit();
          try
          {
            dgv.CurrentCell = nextCell;
          }
          catch (InvalidOperationException) { } //Fails if you have cell validation

        }
      }
    }
  }

To capture the enter key you need to override ProcessCmdKey on the form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {

      if (((keyData & Keys.Enter) == Keys.Enter) && (this.dataGridView1.Focused || ((this.dataGridView1.EditingControl != null) && this.dataGridView1.EditingControl.Focused)))
      {
        this.dataGridView1.MoveNextCell();
        return true;
      }
      else
      {
        return base.ProcessCmdKey(ref msg, keyData);
      }
    }
commented: Excellent! +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.