Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: WPF
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 6-Sep-12 23:11pm

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi Vineetha,
 
you could write something like this:
 
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.
  Permalink  

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



Advertise | Privacy | Mobile
Web04 | 2.8.1411022.1 | Last Updated 7 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100