Click here to Skip to main content
15,880,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,
I'm totally fresher in WPF.I have a DataGrid with 3 columns. As the user enters in data and presses enter key. I want the cell focus to move to the right instead of down .How can i do that in PreviewKeyDown event.

Thanks & Regards,
Vineetha.K.R
Posted

1 solution

Hi Vineetha,

you could write something like this:

C#
PreviewKeyDown(object sender, KeyEventArgs e)
{
  DataGrid grid = (DataGrid)sender;

  if (e.Key == Key.Enter || e.Key == Key.Return)
  {
    // get the selected row
    var selectedRow = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;

    // selectedRow can be null due to virtualization
    if (selectedRow != null)
    {
      // there should always be a selected cell
      if (grid.SelectedCells.Count != 0)
      {
         // get the cell info
         DataGridCellInfo currentCell = grid.SelectedCells[0];

         // get the display index of the cell's column + 1 (for next column)
         int columnDisplayIndex = currentCell.Column.DisplayIndex++;

         // if display index is valid
         if (columnDisplayIndex < grid.Columns.Count)
         {
            // get the DataGridColumn instance from the display index
            DataGridColumn nextColumn = grid.ColumnFromDisplayIndex(columnDisplayIndex);

            // now telling the grid, that we handled the key down event
            e.Handled = true;

            // setting the current cell (selected, focused)
            grid.CurrentCell = new DataGridCellInfo(grid.SelectedItem, nextColumn);

            // tell the grid to initialize edit mode for the current cell
            grid.BeginEdit();
         }
      }
    }
  }
}


Please be aware that I have not checked if this is working.
 
Share this answer
 
Comments
Ahmad_kelany 14-Dec-18 15:13pm    
This doesn't work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900