Category / Section
How to add a new row continuously without any selection to next row in WPF DataGrid (SfDataGrid)?
5 mins read
When pressing the Enter key or Tab key in AddNewRow the selection will be moved to next row at once the new row has been added in WPF DataGrid (SfDataGrid). You can skip this selection using CurrentCellActivated event like below code example.
XAML
<syncfusion:SfDataGrid x:Name="dataGrid" AddNewRowPosition="Top" AllowEditing="True" AllowFiltering="True" AutoGenerateColumns="False" CurrentCellActivated="datagrid_CurrentCellActivated" ItemsSource="{Binding EmployeeDetails}"> <syncfusion:SfDataGrid.Columns> <syncfusion:GridTextColumn MappingName="EmployeeName" /> <syncfusion:GridTextColumn MappingName="EmployeeAge" /> <syncfusion:GridTextColumn MappingName="EmployeeArea" /> <syncfusion:GridTextColumn MappingName="EmployeeGender" /> <syncfusion:GridTextColumn MappingName="ExperienceInMonth" /> <syncfusion:GridCheckBoxColumn MappingName="Review" /> </syncfusion:SfDataGrid.Columns> </syncfusion:SfDataGrid>
C#
private void datagrid_CurrentCellActivated(object sender, CurrentCellActivatedEventArgs args) { //Skip the selection when it is moved to next row on adding new row. bool needToMove = (dataGrid.IsAddNewIndex(args.PreviousRowColumnIndex.RowIndex) && !dataGrid.IsAddNewIndex(args.CurrentRowColumnIndex.RowIndex) && (Keyboard.IsKeyDown(Key.Enter) || Keyboard.IsKeyDown(Key.Tab))); Dispatcher.BeginInvoke(new Action(() => { var gridModel = this.dataGrid.GetGridModel(); var columnIndex = this.dataGrid.GetFirstColumnIndex(); if (needToMove && gridModel != null) { this.dataGrid.MoveCurrentCell(new RowColumnIndex(gridModel.AddNewRowController.GetAddNewRowIndex(), columnIndex)); } }), DispatcherPriority.ApplicationIdle); }
In UWP, you have to use Dispatcher.RunAsync method for instead of Dispatcher.BeginInvoke method like below code example.
C#
private void datagrid_CurrentCellActivated(object sender, CurrentCellActivatedEventArgs args) { //Skip the selection when it is moved to next row on adding new row. bool needToMove = (dataGrid.IsAddNewIndex(args.PreviousRowColumnIndex.RowIndex) && !dataGrid.IsAddNewIndex(args.CurrentRowColumnIndex.RowIndex) && (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Enter).HasFlag(CoreVirtualKeyStates.Down) || Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Tab).HasFlag(CoreVirtualKeyStates.Down))); Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var gridModel = this.dataGrid.GetGridModel(); var columnIndex = this.dataGrid.GetFirstColumnIndex(); if (needToMove && gridModel != null) { this.dataGrid.MoveCurrentCell(new RowColumnIndex(gridModel.AddNewRowController.GetAddNewRowIndex(), columnIndex)); } });a }