Selection
This section explains the selection behavior, properties, and events that participate in Selection and how to customize the selection controller. SfDataGrid supports two type of Selection behaviors.
- Row Selection
- Cell Selection
Row Selection
The SfDataGrid control provides an interactive support to select a specific row or group of rows programmatically or by Mouse and Keyboard interactions. To enable this Selection in SfDataGrid, set SfDataGrid.SelectionUnit property to Row.
Cell Selection
The SfDataGrid control provides interactive support to select a specific cell or group of cells programmatically or by Mouse and Keyboard interactions. To enable this Selection in SfDataGrid, set SfDataGrid.SelectionUnit property to Cell or Any and the SfDataGrid.NavigationMode should be Cell. In Any, you can select all cells in a particular row by clicking RowHeader.
NOTE
HeaderRows and TableSummaryRows do not have support selection.
Properties
SfDataGrid control provides the following properties for Selection.
Properties | Type | Description |
---|---|---|
SelectionUnit | GridSelectionUnit | Gets or sets a value indicating the type of selection in the SfDataGrid control. The different types of selection are Cell, Row, and Any. |
SelectionController | IGridSelectionController | Gets or sets the selection controller to handle the selection operations. It is initialized based on the SelectionUnit value. |
SelectionMode | GridSelectionMode | Gets or sets the selection behavior in the SfDataGrid control. The different modes are Single, Multiple, Extended, and None. |
NavigationMode | NavigationMode | Gets or sets the navigation behavior between rows or cells in the SfDataGrid control. |
AutoScroller.IsEnabled | Boolean | Gets or sets the value indicating whether the AutoScroller is enabled or not. |
AllowSelectionOnPointerPressed | Boolean | Allows selection during PointerPressed event. By default, selection occurs during PointerReleased event. |
SelectedItem | Object | Gets or sets the record of selected row. When you have multiple selections in the SfDataGrid control, then SfDataGrid.SelectedItem returns the record of the initially selected row. This is maintained only in Row selection. |
CurrentItem | Object | Gets or sets the record of current row. When you have multiple selections in the SfDataGrid control, then SfDataGrid.CurrentItem returns the record of current row. |
SelectedItems | ObservableCollection < object > | Gets the collection of selected records. SfDataGrid control also allows you to manipulate this collection. This is maintained only in Row selection. |
CurrentCellInfo | GridCellInfo | Gets the GridCellInfo of a current cell. GridCellInfo contains the record of current row and column of the current cell. This is maintained only in the Cell selection. |
CurrentColumn | GridColumn | Gets the GridColumn of a current cell. |
RowSelectionBrush | Brush | Gets or sets the brush value for selection background in the Data Row. |
GroupRowSelectionBrush | Brush | Gets or sets the brush value for selection background in the Group caption Row. |
CurrentCellBorderBrush | Brush | Gets or sets the Border color of the current cell when NavigationMode is in the Cell. |
CurrentCellBorderThickness | Thickness | Gets or sets the Border width of Current cell when NavigationMode is in the Cell |
NOTE
In WPF, MouseDown event is triggered after releasing the finger from touch. So, AllowSelectionOnPointerPressed API only works for mouse in WPF.
Methods
SfDataGrid control supports the following public methods for selection:
- SelectAll-Selects all the rows or cells in the SfDataGrid. This method does not make any changes when the selection mode is set to Single or None.
The following code example illustrates how to call SelectAll () method.
private void SelectAll_Click(object sender, RoutedEventArgs e)
{
dataGrid.SelectionMode = GridSelectionMode.Multiple;
dataGrid.SelectAll();
}
When the above code example is run, all the rows or cells are selected as displayed in the screenshot.
- ClearSelections-Clears all the selections in the SfDataGrid.
The following code example illustrates how to use ClearSelections(bool exceptCurrentRow). When exceptCurrentRow is set to true, the current row is not cleared; otherwise, all the selections are cleared.
private void ClearSelection_Click(object sender, RoutedEventArgs e)
{
dataGrid.ClearSelections(true);
}
- MoveCurrentCell-Moves the current cell to the corresponding row column index. This method works only when NavigationMode is set to Cell.
The following code example explains you how to use MoveCurrentCell (RowColumnIndex rowColumnIndex). To use RowColumnIndex structure, add Syncfusion.UI.Xaml.ScrollAxis reference.
private void MoveCurrentCell_Click(object sender, RoutedEventArgs e)
{
RowColumnIndex rowColumnIndex = new RowColumnIndex();
rowColumnIndex.ColumnIndex =2;
rowColumnIndex.RowIndex = 2;
dataGrid.MoveCurrentCell(rowColumnIndex);
}
The current cell is moved to the third column (‘0’ based index), second row in the screenshot.
- ScrollInView-You can scroll the view to a particular record by using ScrollInView (RowColumnIndex rowColumnIndex) method where you can view the record that is not in view also.
dataGrid.ScrollInView(new RowColumnIndex() { RowIndex = dataGrid.ResolveToRowIndex(7), ColumnIndex = 1 });
- SelectRows-You can select a range of rows programmatically by using SelectRows method. This method is effective only in Row selection and the SelectionMode should be Multiple or Extended.
The following code example illustrates how to use SelectRows(int startRowIndex, int endRowIndex) .
private void SelectRows_Click(object sender, RoutedEventArgs e)
{
int rowIndex = this.dataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
this.dataGrid.SelectRows(rowIndex, rowIndex + 4);
}
- SelectCell-You can select a specific cell programmatically by using SelectCell method. This method is effective only in Cell selection.
The following code example shows how to use SelectCell(object rowData, GridColumn column) method.
private void SelectCell_Click(object sender, RoutedEventArgs e)
{
OrderInfoViewModel viewModel = this.dataGrid.DataContext as OrderInfoViewModel;
this.dataGrid.SelectCell(viewModel.OrdersListDetails[3], this.dataGrid.Columns["CustomerID"]);
}
- SelectCells-You can select a range of cells programmatically by using SelectCells method. This method is effective only in Cell selection and the SelectionMode should be Multiple or Extended.
The following code example shows how to use SelectCells (object startRowData, GridColumn startColumn, object endRowData, GridColumn endColumn) method.
private void SelectCells_Click(object sender, RoutedEventArgs e)
{
OrderInfoViewModel viewModel = this.dataGrid.DataContext as OrderInfoViewModel;
object startRowData = viewModel.OrdersListDetails[3];
object endRowData = viewModel.OrdersListDetails[6];
GridColumn startColumn = this.dataGrid.Columns["CustomerID"];
GridColumn endColumn = this.dataGrid.Columns["ShipCountry"];
this.dataGrid.SelectCells(startRowData, startColumn, endRowData, endColumn);
}
- UnSelectCell-You can remove the selection from a specific cell programmatically by using UnSelectCell method. This method is effective only in Cell selection.
The following code example shows how to use UnSelectCell(object rowData, GridColumn column) method.
private void UnSelectCell_Click(object sender, RoutedEventArgs e)
{
OrderInfoViewModel viewModel = this.dataGrid.DataContext as OrderInfoViewModel;
this.dataGrid.UnSelectCell(viewModel.OrdersListDetails[3], this.dataGrid.Columns["CustomerID"]);
}
- UnSelectCells-You can remove the selection from a range of cells programmatically by using UnSelectCells method. This method is effective only in the Cell selection and the SelectionMode should be Multiple or Extended.
The following code example shows how to use UnSelectCells(object startRowData, GridColumn startColumn, object endRowData, GridColumn endColumn) method.
private void UnSelectCells_Click(object sender, RoutedEventArgs e)
{
OrderInfoViewModel viewModel = this.dataGrid.DataContext as OrderInfoViewModel;
object startRowData = viewModel.OrdersListDetails[3];
object endRowData = viewModel.OrdersListDetails[6];
GridColumn startColumn = this.dataGrid.Columns["CustomerID"];
GridColumn endColumn = this.dataGrid.Columns["ShipCountry"];
this.dataGrid.UnSelectCells(startRowData, startColumn, endRowData, endColumn);
}
- GetSelectedCells-Returns the collection of GridCellInfo that contains information about the selected cell. This method is effective only in the Cell selection.
The following code example shows how to use GetSelectedCells() method.
List<GridCellInfo> selectedCells = this.dataGrid.GetSelectedCells();
Events
SfDataGrid control provides the following two events during the selection operation:
- SfDataGrid.SelectionChanging:Triggers while selecting a row or cell. This event helps to cancel the selection operation.
- SfDataGrid.SelectionChanged:Triggers after row selection.
The following code example illustrates SelectionChanging event purpose.
void dataGrid_SelectionChanging(object sender, GridSelectionChangingEventArgs e)
{
e.Cancel = true;
}
These two events are triggered with GridSelectionChangingEventArgs and GridSelectionChangedEventArgs that contain the following properties.
- AddedItems-Gets the collection of GridRowInfo or GridCellInfo that is added for selection.
- RemovedItems-Gets the collection of GridRowInfo or GridCellInfo that is removed from the selection.
NOTE
GridRowInfo is used in Row selection and GridCellInfo is used in Cell selection.
RowSelection
SfDataGrid control provides an interactive support for selecting rows in different modes in a smooth and easy manner.
In Row selection, the SfDataGrid.SelectionController.SelectedRows property is maintained that holds the collection of GridRowInfo. GridRowInfo has the following properties:
- RowData-Returns the record when the selected row is DataRow, otherwise returns null.
- RowIndex-Returns the row index of the selected row.
- IsDataRow-Returns the value indicating whether the selected row is DataRow.
- IsAddNewRow-Returns the value indicating whether the selected row is AddNewRow.
SelectionMode
Row Selection has different modes to do the selection as follows.
- Single:In the Single mode, the SfDataGrid control enables you to select a single row only. You cannot select more than one row by using Shift or Ctrl key.
- Multiple: In Multiple mode, the SfDataGrid enables you to select more than one row. Selection is not cleared when selecting more than one record. When you click on a selected row, selection is cleared, but the current cell selection is maintained when NavigationMode is Cell. You can also select more than one row by dragging the mouse, but the selection is not cleared in the previously selected rows.
- Extended: In the Extended mode, the SfDataGrid enables you to select multiple rows. Selection is cleared when selecting more than one cell without pressing Shift or Ctrl in the SfDataGrid control. In this mode, you can also select multiple rows in a smooth way by dragging the mouse.
- None: The SfDataGrid control disables selection when the selection type is set to None.
By default, the selection mode is set to Single mode. You can assign the selection mode for the SfDataGrid control by using SfDataGrid.SelectionMode property.
The following code example illustrates how to set a selection mode for the SfDataGrid control.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding ItemsSource}"
SelectionUnit="Row"
SelectionMode="Extended" />
dataGrid.SelectionMode = Syncfusion.UI.Xaml.Grid.GridSelectionMode.Extended;
Navigation Mode
Another vital operation in selection with editing is NavigationMode. SfDataGrid control provides the following two types of NavigationModes.
- Row: This mode does not show the current cell selection and disables cell editing.
- Cell: This mode shows the current cell and enables editing the cell.
NOTE
Cell based key navigation is disabled in Row navigation mode.
The following code example shows a SfDataGrid in row navigation mode.
<syncfusion:SfDataGrid x:Name="datagrid"
ItemsSource="{Binding ItemsSource}"
NavigationMode="Row"
SelectionUnit="Row"
SelectionMode="Extended" />
The following screenshot shows SfDataGrid in the Row Navigation Mode.
The following screenshot shows SfDataGrid in the Cell Navigation Mode.
Cell Selection
SfDataGrid control provides an interactive support for selecting cells in different modes with smooth and easy manner.
In Cell Selection, the SfDataGrid.SelectionController.SelectedCells property is maintained and that holds the collection of GridSelectedCellsInfo. GridSelectedCellsInfo has the following properties.
- RowData-Returns the record when the selected cell is DataRow, otherwise returns null.
- ColumnCollection-Returns the collection of GridColumn that have been selected in DataRow.
- RowIndex-Returns the row index when the selected cell is SummaryRow or AddNewRow, otherwise returns-1.
- IsDataRow-Returns the value indicating if the selected cell is DataRow.
- IsAddNewRow-Returns the value indicating if the selected cell is AddNewRow.
SelectionMode
Cell Selection has different modes to select the cells in the SfDataGrid control.
- Single: In Single mode, the SfDataGrid control enables you to select a single Cell only. You cannot select more than one Cell by using Shift or Ctrl key.
- Multiple: In Multiple modes, the SfDataGrid enables you to select more than one Cell. When you click a selected Cell, the selection is cleared, but the current cell selection is maintained on the same cell. You can also select more than one cell by dragging the mouse, but the selection is not cleared in this mode of selection.
- Extended: In Extended mode, the SfDataGrid enables you to select multiple Cells. The previously selected cells are cleared when selecting any cell without pressing SHIFT or CTRL keys. In this mode, you can also select multiple cells by dragging the mouse over the GridCells.
- None: The SfDataGrid control disables selection when the selection type is set to None.
By default, the selection mode is set to the Single mode. You can assign the selection mode for SfDataGrid control by using SfDataGrid.SelectionMode property.
Navigation Mode
In Cell selection, NavigationMode should always be Cell instead of Row. Selection is not maintained as expected when NavigationMode is set as Row.
The following code example shows SfDataGrid in the Cell selection.
<syncfusion:SfDataGrid x:Name="syncgrid"
ItemsSource="{Binding OrdersListDetails}"
SelectionUnit="Cell"
NavigationMode="Cell"
SelectionMode="Extended">
The following screenshot shows SfDataGrid in the Cell Selection.
Customizing Selection operations
Selection related operations are handled in Selection Controllers of the SfDataGrid and it is possible to override and customize the Selection Controller to achieve some custom behaviors. The selection controller class hierarchy is as follows.
The GridSelectionController and GridCellSelectionController have been derived from the GridBaseSelectionController that contains abstract methods and properties. You can customize the selection behaviors in two different controllers, GridSelectionController and GridCellSelectionController.
- GridSelectionController: GridSelectionController is responsible for Row selection. The selection related operations are handled by this controller when SfDataGrid.SelectionUnit is set to Row.
- GridCellSelectionController: GridCellSelectionController is responsible for Cell selection. The selection related operations are handled by this controller when SfDataGrid.SelectionUnit is set to Cell or Any.
Properties
GridBaseSelectionController contains the following properties to handle the selection.
Properties | Description |
---|---|
CurrentCellManager |
Gets or sets the current cell manager of the SfDataGrid.
Note: You can edit and navigate the current cell by using CurrentCellManager |
SelectedRows | Gets the collection of the GridRowInfo that is selected row information in the SfDataGrid control. SelectedRows are maintained only in Row selection. |
SelectedCells | Gets the collection of the GridSelectedCellsInfo that is selected cells information in the SfDataGrid control. SelectedCells are maintained only in Row selection |
IsSuspended | Gets or sets the value indicating that the selection process is suspended or not. It is suspended for selection property changes in internal codes. |
RowHoverBackgroundBrush | Gets or sets the brush value for Row hover highlighting. |
RowSelectionBrush | Gets or sets the brush value for Row Selection. |
GroupRowSelectionBrush | Gets or sets the brush value for Selection brush in group caption and group summary rows. |
Methods
GridBaseSelectionController contains some important methods to handle selection as follows.
Methods | Description |
---|---|
CreateCurrentCellManager | Creates the new instance for CurrentCellManager property. |
ProcessOnAddNewRow | Updates the selection when a new row is committed or changes the position of the AddNewRow. |
ProcessOnSortChanged | Updates the selection based on SelectedRows or SelectedCells when sorting is applied to any column. |
ProcessOnFilterPopupOpened | Updates the selection when AddNewRow is in EditMode. |
ProcessOnFilterApplied | Updates the selection based on SelectedRows or SelectedCells when filtering is applied on any column. |
ProcessOnPageChanged | Updates the selection when you move on to the next page. |
ProcessOnGroupChanged | Updates the selection based on SelectedRows or SelectedCells when grouping is applied for any column. |
ClearDetailsViewGridSelections | Clears all the selection in the specified nested grid. |
AutoScrollerValueChanged | Invoked when AutoScroller scrolls the rows or columns. |
CheckIsLastRow | Returns the value indicating whether the current row is the last row for all parent and child grids. |
Methods | Description |
---|---|
HandlePointerOperation | Handles all pointer operations (Pressed, Release, Moved, Tapped, and Double-Tapped) that are performed in the grid cell. |
HandleKeyDown | Handles all key operations of the SfDataGrid. |
HandleGridOperations | Handles all the SfDataGrid operations (Sorting, Filtering, Grouping, Paging, AddNewRow, and Pasting operations) that are performed in the SfDataGrid control. |
HandleSelectionPropertyChanged | Handles when Selection property values (SelectedIndex, SelectedItem and SelectionMode) are changed. |
HandleCollectionsChanged | Handles when the collection change operations (SelectedItems, Columns and DataSource) are performed. |
HandleGroupExpandAndCollapse | Handles when group expands or collapses. |
HandleDetailsViewPointerOperations | Handles pointer operations on the DetailsView Grid. |
HandleDetailsViewKeyOperations | Handles key operations on the DetailsView Grid. |
ClearSelections | Clears all the selection and removes the current cell. The current row selection is not removed when exceptCurrentRow is set to true. |
Customizing Row Selection
Many of the supplementary properties and methods involved in the selection operation of GridSelectionController implement the GridBaseSelectionController. You can customize the Row selection behavior by overriding some methods in the GridSelectionController.
Methods
The following list provides some important methods that are defined in the GridSelectionController.
Methods | Description |
---|---|
ProcessPointerPressed | Invoked when unhandled MouseDown event occurs in GridCell. This method is implemented to handle the selection in SfDataGrid control for this event. |
ProcessPointerReleased | Invoked when unhandled MouseUp event occurs in GridCell. This method is implemented to handle the selection in SfDataGrid control for this event. |
ProcessPointerMoved | Invoked when unhandled MouseMove event occurs in GridCell. This method is implemented to handle the selection in SfDataGrid control for this event. |
ProcessKeyDown | Invoked when unhandled KeyDown event occurs in GridCell. This method is implemented to handle selection and editing in SfDataGrid control for this event. |
ProcessOnTapped | Invoked when single click on a GridCell. It moves the CurrentCell to an edit mode when EditTrigger is set to OnTap. |
ProcessOnDoubleTapped | Invoked when you double click a GridCell. It moves the CurrentCell to an edit mode when EditTrigger is set to OnDoubleTap. |
AddSelection | Adds the selection to the specified rows. |
RemoveSelection | Removes the selection from the specified rows. |
RefreshSelectedRows | Updates the selection in the SfDataGrid control based on the SelectedRows collection. |
RefreshSelectedItems | Updates the selection in the SfDataGrid control based on the SfDataGrid.SelectedItems collection. |
ProcessCurrentItemChanged | Updates the current cell selection in the SfDataGrid control based on the value changed in the CurrentItem. This method moves the current cell to the specified current item. |
ProcessSelectedItemChanged | Updates the selection in the SfDataGrid control based on the value changed in the SelectedItem. |
ProcessSelectedItemsChanged | Updates the selection in the SfDataGrid control based on the manipulation done in the SelectedItems collection. |
RemoveRows | Removes the selected records from the SfDataGrid control. |
The following code example illustrates override methods and how to handle operations. The extended class GridSelectionControllerExt is your new SelectionController. Therefore, you need to assign newly created one to the existing SelectionController that overrides the existing SelectionController. The following code example shows how to select a row based on values in the specific column. This can be achieved by overriding the ProcessPointerReleased method in the GridSelectionController.
dataGrid.SelectionController = new GridSelectionControllerExt(dataGrid);
…
public class GridSelectionControllerExt : GridSelectionController
{
public GridSelectionControllerExt(SfDataGrid dataGrid)
: base(dataGrid)
{ }
protected override void ProcessPointerReleased(MouseButtonEventArgs args, Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex rowColumnIndex)
{
if (this.DataGrid.SelectionMode == GridSelectionMode.Multiple)
{
var previousCurrentRowColumnIndex = this.CurrentCellManager.CurrentRowColumnIndex;
if (!this.CurrentCellManager.HandlePointerOperation(args, rowColumnIndex))
return;
var record = this.DataGrid.GetRecordAtRowIndex(rowColumnIndex.RowIndex);
if (record == null)
return;
var propertyDescriptor = this.DataGrid.View.GetPropertyAccessProvider();
var cellValue = propertyDescriptor.GetValue(record, "ShipCountry");
var records = this.DataGrid.View.Records.Where(item => (item.Data as Orders).ShipCountry.Equals(cellValue));
records.ForEach(item =>
{
int rowIndex = this.DataGrid.ResolveToRowIndex(((Syncfusion.Data.RecordEntry)item).Data);
this.ProcessSelection(rowIndex, previousCurrentRowColumnIndex, SelectionReason.PointerReleased);
});
}
else
base.ProcessPointerReleased(args, rowColumnIndex);
}
}
Customizing Cell Selection
You can customize the Cell selection by overriding the GridCellSelectionController that is implemented from the GridBaseSelectionController. You can change the behavior of the Cell selection by overriding some virtual methods in the GridCellSelectionController.
Methods
The following list provides some important public methods that are defined in the GridCellSelectionController.
Methods | Description |
---|---|
ProcessPointerPressed | Invoked when an unhandled MouseDown event occurs in the GridCell. This method is implemented to handle the selection in the SfDataGrid control for this event. |
ProcessPointerReleased | Invoked when unhandled MouseUp event occurs in the GridCell. This method is implemented to handle the selection in the SfDataGrid control for this event. |
ProcessPointerMoved | Invoked when an unhandled MouseMove event occurs in the GridCell. This method is implemented to handle the selection in the SfDataGrid control for this event. |
ProcessKeyDown | Invoked when an unhandled KeyDown event occurs in the GridCell. This method is implemented to handle selection and for editing in the SfDataGrid control for this event. |
ProcessOnTapped | Invoked when you single click on a GridCell. It moves the CurrentCell to an edit mode when EditTrigger is set to OnTap. |
ProcessOnDoubleTapped | Invoked when you double click on a GridCell. It moves the CurrentCell to an edit mode when EditTrigger is set to OnDoubleTap. |
AddSelection | Adds the selection to the specified cells. |
RemoveSelection | Removes the selection from the specified cells. |
ProcessCurrentItemChanged | Updates the current cell selection in the SfDataGrid control based on the value changed in the CurrentItem. This method moves the current cell to the specified current item. |
The following code example shows how to override the GridCellSelectionController. Here the new class GridCellSelectionControllerExt is created and assigned to the SfDataGrid.SelectionController. This code shows how to change the RowSelectionBrush when pressing down the arrow key. It should be changed when the Freight value of the record is greater than 100.
dataGrid.SelectionController = new GridCellSelectionControllerExt(dataGrid);
…
public class GridCellSelectionControllerExt : GridCellSelectionController
{
public GridCellSelectionControllerExt(SfDataGrid dataGrid)
: base(dataGrid)
{
}
protected override void ProcessKeyDown(KeyEventArgs args)
{
if (args.Key == Key.Down || (args.Key == Key.Enter && !SelectionHelper.CheckControlKeyPressed()))
{
if(this.DataGrid.SelectedDetailsViewGrid != null && this.DataGrid.IsInDetailsViewIndex(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex))
{
this.DataGrid.SelectedDetailsViewGrid.SelectionController.HandleKeyDown(args);
return;
}
var previousRowColumnIndex = this.CurrentCellManager.CurrentRowColumnIndex;
int nextRowIndex = this.GetNextRowIndex(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex);
int lastRowIndex = this.DataGrid.ResolveToRowIndex(this.DataGrid.View.Records.Count - 1);
if (nextRowIndex >= lastRowIndex && nextRowIndex == this.CurrentCellManager.CurrentRowColumnIndex.RowIndex)
return;
if (SelectionHelper.CheckShiftKeyPressed() && this.DataGrid.SelectionMode == GridSelectionMode.Extended && this.CurrentCellManager.CurrentRowColumnIndex.RowIndex == nextRowIndex)
nextRowIndex = this.GetNextRowIndex(nextRowIndex);
if (this.DataGrid.DetailsViewDefinition.Count > 0)
{
var record = this.DataGrid.GetRecordAtRowIndex(nextRowIndex);
while (this.DataGrid.IsInDetailsViewIndex(nextRowIndex))
{
nextRowIndex = this.GetNextRowIndex(nextRowIndex);
if (record == null)
return;
}
}
RowColumnIndex rowColIndex = new RowColumnIndex(nextRowIndex, this.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex);
if (!this.CurrentCellManager.HandleKeyNavigation(args, rowColIndex))
return;
if (SelectionHelper.CheckShiftKeyPressed())
this.ProcessShiftSelection(rowColIndex, previousRowColumnIndex, args.Key);
else
this.ProcessSelection(rowColIndex, SelectionReason.KeyPressed);
this.ScrollInViewFromBottom(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex);
args.Handled = true;
}
else if (args.Key == Key.Up)
{
if (this.DataGrid.SelectedDetailsViewGrid != null && this.DataGrid.IsInDetailsViewIndex(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex))
{
this.DataGrid.SelectedDetailsViewGrid.SelectionController.HandleKeyDown(args);
return;
}
var previousRowColumnIndex = this.CurrentCellManager.CurrentRowColumnIndex;
int prevRowIndex = this.GetPreviousRowIndex(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex);
int actualIndex = prevRowIndex;
if (actualIndex <= this.DataGrid.ResolveStartIndexBasedOnPosition() && actualIndex == this.CurrentCellManager.CurrentRowColumnIndex.RowIndex)
return;
if (SelectionHelper.CheckShiftKeyPressed() && this.DataGrid.SelectionMode == GridSelectionMode.Extended && this.CurrentCellManager.CurrentRowColumnIndex.RowIndex == actualIndex)
actualIndex = this.GetPreviousRowIndex(actualIndex);
if (this.DataGrid.DetailsViewDefinition.Count > 0)
{
while (this.DataGrid.IsInDetailsViewIndex(actualIndex))
{
actualIndex = this.GetPreviousRowIndex(actualIndex);
if (actualIndex == this.DataGrid.ResolveStartIndexBasedOnPosition())
return;
}
}
RowColumnIndex rowColumnIndex = new RowColumnIndex(actualIndex, this.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex);
if (!this.CurrentCellManager.HandleKeyNavigation(args, rowColumnIndex))
return;
if (SelectionHelper.CheckShiftKeyPressed())
this.ProcessShiftSelection(rowColumnIndex, previousRowColumnIndex, args.Key);
else
this.ProcessSelection(rowColumnIndex, SelectionReason.KeyPressed);
this.ScrollInViewFromTop(this.CurrentCellManager.CurrentRowColumnIndex.RowIndex);
args.Handled = true;
}
else
base.ProcessKeyDown(args);
}
}
NOTE
To use the GetRecordAtRowIndex method, refer to Syncfusion.UI.Xaml.Grid.Helper.
CurrentCell and Navigation
GridCurrentCellManager provides support to edit and navigate current cell navigation operations in the SfDataGrid. You can access the GridCurrentCellManager by using SfDataGrid.SelectionController.CurrentCellManager property.
Properties
Properties | Description |
---|---|
CurrentRowColumnIndex | Gets or sets the current cell row and column index. |
CurrentCell | Gets or sets the current cell column base. |
HasCurrentCell | Checks the value of the current cell. Returns True when the current cell column base value is not null. |
Methods
Methods | Description |
---|---|
BeginEdit | Starts an edit operation in the current cell. |
EndEdit | Ends an edit operation in the current cell. |
Events
Events | Description |
---|---|
CurrentCellActivatingEvent | Triggered when the CurrentCell is moving from one cell to another. |
CurrentCellActivatedEvent | Triggered when the CurrentCell is moved from one cell to another. |
CurrentCellBeginEditEvent | Triggered when the CurrentCell goes to edit mode. |
CurrentCellEndEditEvent | Triggered when the CurrentCell goes to normal mode from the edit mode. |
The following code example illustrates how to access CurrentCell related information.
var currentCell= dataGrid.SelectionController.CurrentCellManager.CurrentCell;
The following list provides navigation on the Grid cell in the SfDataGrid. It needs NavigationMode as Cell and SelectionMode as Single, Multiple, or Extend to navigate. This list provides you navigation behavior with Single selection mode. In all cases selection is also changed.
Events | Description |
---|---|
Up/Down, Shift+Up/Down | Current cell or current row moves upward or downward. |
CTRL+Up/Down | CurrentCell or Row moves to the First or last row. |
Right/Left | CurrentCell moves to the next cell within the same row. |
CTRL+Right/Left | CurrentCell moves to the right end or left end of the last cell of the same row. |
PageUp/PageDown | CurrentCell or row moves to the first and the last visible row. |
Home/End | Current cell moves to the last or first cell of the same row. |
CTRL+Home/End | CurrentCell moves to the first cell of the first row or the last cell of the last row. |
Tab | CurrentCell moves to the next cell. |
Shift+Tab | CurrentCell moves to the previous cell. |
Enter | CurrentCell moves downward (next row). |
CTRL+Enter | EndEdit and remains in the same cell. |
Space | Only in the Multiple selection mode to select or unselect specific row or cell. |
NOTE
The listed key navigation behaves the same as multiple selection, but the current cell moves selection and does not move in single selection. In extended mode, all selection modes are like single mode other than Shift+UP/Down selects multiple records and moves towards its direction.
You can stop the navigation by canceling CurrentCellActivating event. The following code example describes that.
void dataGrid_CurrentCellActivating(object sender, CurrentCellActivatingEventArgs args)
{
args.Cancel = true;
}
Clipboard Operations
This section explains you about the Clipboard operations support in the SfDataGrid and how to customize the Clipboard operations by overriding the GridCutCopyPaste class.
Overview
SfDataGrid supports the Clipboard operations such as cut, copy and paste data within the SfDataGrid control and between the other applications such as Notepad.
Copy and Paste Option
In the SfDataGrid, by setting GridCopyOption and GridPasteOption properties,you can define the behaviors of cut, copy, and paste. The default value of the GridCopyOption is CopyData and GridPasteOption is PasteData.
GridCopyOption
- None: Disables copy in the SfDataGrid.
- CopyData: Copies the selected records from the SfDataGrid.
- CutData: Cuts the selected records from the SfDataGrid.
- IncludeHeaders: Copies the selected records from the SfDataGrid, including the corresponding headers when setting along with the CopyData or CutData.
- IncludeFormat: Copies the selected records from the SfDataGrid along with its format.
GridPasteOption
- None: Disables paste in the SfDataGrid.
- PasteData: Enables paste operation from the clipboard to theSfDataGrid. When the incompatible value is pasted into a cell, pasting operation is skipped for that particular cell.
- ExcludeFirstLine: Pastes the data from the clipboard onto the SfDataGrid without the first line of the clipboard.
The following code example shows you how to define the cut, copy and paste behaviors.
//Copies or Cuts the record with Header and Format
this.dataGrid.GridCopyOption = GridCopyOption.CutData | GridCopyOption.CopyData | GridCopyOption.IncludeHeaders | GridCopyOption.IncludeFormat;
//Pastes the data with ExcludeFirstLine
this.dataGrid.GridPasteOption = GridPasteOption.PasteData | GridPasteOption.ExcludeFirstLine;
Events
The SfDataGrid control provides the following events while performing clipboard operations
GridCopyContent
This event is triggered when copying or cutting the data in the SfDataGrid. The GridCopyContentEventArgs object contains the Handled property. When it is set to true, it indicates that the event is handled and you can change the behavior of the copy or cut based on your requirement.
GridPasteContent
This event is triggered when pasting the data in the SfDataGrid. The GridCopyContentEventArgs object contains the Handled property. When it is set to true, it indicates that the event is handled and you can change the behavior of the paste based on your requirement.
CopyGridCellContent
This event is triggered when the copy operation is performed for each cell. A GridCopyPasteCellEventArgs object contains the Handled property. When it is set to true, it indicates that the event is handled and that particular cell is not copied in the clipboard. A GridCopyPasteCellEventArgs object contains the following arguments.
- Column: It contains the corresponding column of a particular cell.
- RowData: It contains the respective row data of a particular cell.
- ClipBoardValue: It contains the respective copied CellValue of a particular cell.
PasteGridCellContent
This event is triggered when the paste operation is performed for each cell. A GridCopyPasteCellEventArgs object contains the Handled property. When it is set to true, it indicates that the event is handled and that particular cell is not pasted in the SfDataGrid. A GridCopyPasteCellEventArgs object contains the following argument.
- Column: It contains the corresponding column of a particular cell.
- RowData: It contains the respective row data of a particular cell.
- ClipBoardValue: It contains the respective copied data for a particular cell.
Methods
The SfDataGrid.GridCopyPaste contains the following methods to perform the clipboard operations from the coding.
S. No | Method Name | Property Type | Description |
---|---|---|---|
1 | Cut | Cut() | This method copies the selected records and sets the default value or null or empty. This method is called by using Ctrl+x. |
2 | Copy | Copy() | This method copies the selected records. This method is called by using Ctrl+c. |
3 | Paste | Paste() | This method pastes the selected records. This method is called by using Ctrl+v. |
4 | CopyRowsToClipboard | CopyRowsToClipboard(int startRecordIndex, int endRecordIndex) | This method copies the data from the start record index to end record index. |
The following code example shows how to call the above methods to process the clipboard operations.
this.datagrid.GridCopyPaste.Cut();
this.datagrid.GridCopyPaste.Copy();
this.datagrid.GridCopyPaste.Paste();
Overriding the GridCutCopyPaste
You can customize the cut, copy and paste operations in the SfDataGrid by overriding the GridCutCopyPaste class that is implemented from the IGridCopyPaste interface. Following are the methods present in the GridCutCopyPaste class where you can override and customize the copy paste operations. Refer to the How To section to see the examples to override the GridCutCopyPaste class.
The following code example shows how to assign the overriding class to the SfDataGrid.GridCopyPaste.
this.dataGrid.GridCopyPaste = new CustomCopyPaste(dataGrid);
Copy
Method Name | Parameters | Description |
---|---|---|
CopyTextToClipBoard | CopyTextToClipBoard ( ObservableCollection < object > records, bool cut ) | Sorts the SelectedRecords in a order that is present in the SfDataGrid and invokes the CopyRows method. When you are processing the cut operation, it invokes the ClearCellsByCut method also. |
CopyRows | CopyRows ( ObservableCollection < object > CopiedRecords, ref StringBuilder text ) | Invokes the CopyRow method by passing each record in the CopiedRecords. |
CopyRow | CopyRow ( object record, ref StringBuilder text ) | Invokes the CopyCell method by passing the copied record and each column in the SfDataGrid.Columns. |
CopyTextToClipBoard | CopyTextToClipBoard ( GridSelectedCellsCollection selectedCells, bool cut ) | Invokes the CopyCells method. When you process the cut operation, it invokes the ClearCellsByCut method. |
CopyCells | CopyCells ( GridSelectedCellsCollection selectedCells, StringBuilder text ) | Sorts the selected cells in a order present in the SfDataGrid and invokes the CopyCellRow by passing the SelectedCellInfo. |
CopyCellRow | CopyCellRow ( GridSelectedCellsInfo cellRow, ref StringBuilder text ) | Invokes the CopyCell by passing the copied record and Column. |
CopyCell | CopyCell ( object record, GridColumn column, ref StringBuilder text ) | Based on a row data and column, it gets the corresponding cell value. |
Cut
S. No | Method Name | Property Type | Description |
---|---|---|---|
1 | ClearCellsByCut | ClearCellsByCut ( ObservableCollection < object > selectedCells ) | Separates the record, columns and invokes the CutRowCell method. |
2 | CutRowCell | CutRowCell ( object rowData, GridColumn column ) | Property in a rowData corresponding to the column resets to its default value. |
Paste
S. No | Method Name | Property Type | Description |
---|---|---|---|
1 | PasteTextToRow | PasteTextToRow() | Separates the clipboard content into the number of rows and invokes PasteToRows method by passing the copied clipboard text rows. |
2 | PasteToRows | PasteToRows ( object copiedRecords ) | Gets the selected records and invokes the PasteToRow method by passing the clipboard text row and selected record. |
3 | PasteToRow | PasteToRow ( object copiedRecord, object selectedRecords ) | Separates the clipboard text rows and invokes the PasteToCell method by passing the selected record, column and clipboard text. |
4 | PasteTextToCell | PasteTextToCell() | Separates the clipboard content into the number of clipboard text rows and invokes PasteToCells method by passing the copied records. |
5 | PasteToCells | PasteToCells ( object copiedRecords ) | Gets the selected records and invokes the PasteToRow method by passing the clipboard text record and selected record. |
6 | PasteToCell | PasteToCell ( object copyValue, GridColumn column, object rowData ) | Checks the column type and gets the provider and invokes CommitValue method by passing rowData, column, provider, copied value. |
7 | CommitValue | CommitValue ( object rowData, GridColumn column, IPropertyAccessProvider provider, object changedValue ) | Gets the type of paste column from the GetPropertyType method. Checks that copy text to paste column type by using CanConvertToType method and sets the clipboard text value to selected cell. |
8 | GetPropertyType | GetPropertyType ( GridColumn column, object rowData ) | Gets the type of paste column from GetPropertyType method. Checks that copy text to paste column type by using CanConvertToType method and sets the clipboard value to selected cell. |
9 | CanConvertToType | CanConvertToType ( object value, ref Type type ) | Checks whether the copied text is compatible for pasting or not. |
Following layout shows the methods flow in the GridCutCopyPaste where you can override.
Copy Operation
Cut Operation
Paste Operation
How to
How to copy one cell and paste into many cells
By default, you can able to copy one cell and paste into another cell when cell selection is enabled in the SfDataGrid. The following code example shows how to copy one cell and paste into all the selected cells by overriding the PasteToCell method in the GridCutCopyPaste class. Here, the new class CustomCopyPaste is created and assigned to the SfDataGrid.GridCopyPaste.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding Products}"
SelectionUnit="Cell"
SelectionMode="Extended"
AutoGenerateColumns="True"/>
this.dataGrid.GridCopyPaste = new CustomCopyPaste(dataGrid);
…….
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
async protected override void PasteToCell(object record, GridColumn column, object rowData)
{
DataPackageView dataPackageView = Clipboard.GetContent();
String text = null;
if (dataPackageView.Contains(StandardDataFormats.Text))
text = await dataPackageView.GetTextAsync();
string[] clipboardText = Regex.Split(text, @"\r\n");
clipboardText = Regex.Split(clipboardText[0], @"\t");
//Gets the ClipboardText and checks whether the clipboard text is more than one cell or not
//Calls the base.
if (clipboardText.Count() > 1)
{
base.PasteToCell(record, column, rowData);
return;
}
//Gets the selected cells for paste the copied cell
var selectedCells = this.dataGrid.GetSelectedCells();
int selectedCellsCount = selectedCells.Count;
for (int i = 0; i < selectedCellsCount; i++)
{
record = selectedCells[i].RowData;
column = selectedCells[i].Column;
//Calls the PasteToCell method with particular record of selectedCells,
// Column of selected records and rowdata
base.PasteToCell(record, column, rowData);
}
}
}
How to copy one row and paste into many rows
By default, you can able to copy one row and paste into another row. The following code example shows how to copy the one row and paste into all selected rows by overriding the PasteToRow method in the GridCutCopyPaste class. Here, the new class CustomCopyPaste is created and assigned to the SfDataGrid.GridCopyPaste.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding Products}"
SelectionUnit="Row"
SelectionMode="Extended"
AutoGenerateColumns="True"/>
this.dataGrid.GridCopyPaste = new CustomCopyPaste(dataGrid);
…….
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
async protected override void PasteToRow(object copiedRecord, object selectedRecords)
{
DataPackageView dataPackageView = Clipboard.GetContent();
String text = null;
if (dataPackageView.Contains(StandardDataFormats.Text))
text = await dataPackageView.GetTextAsync();
string[] clipboardText = Regex.Split(text, @"\r\n");
//Gets the ClipboardText and checks whether the clipboard text is more than one row or not
//Calls the base.
if (clipboardText.Count() > 1)
{
base.PasteToRow(copiedRecord, selectedRecords);
return;
}
var selectedRecord = this.dataGrid.SelectedItems;
for (int i = 0; i < selectedRecord.Count; i++)
{
//Gets the Selected records for paste the copied row.
selectedRecords = selectedRecord[i];
// Calls the PasteToRow method with copiedRecord and selectedRecord
base.PasteToRow(copiedRecord, selectedRecords);
}
}
}
How to select the pasted records after pasting
By default, after pasting also, the SfDataGrid maintains the previously selected records. When you want to select the pasted records after paste operation, then you can achieve your requirement by overriding the PasteToRows and PasteToRow methods in the GridCutCopyPaste class. Here, the new class CustomCopyPaste is created and assigned to the SfDataGrid.GridCopyPaste. This code is applicable for SelectionUnit as Row.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding Products}"
SelectionUnit="Row"
SelectionMode="Extended"
AutoGenerateColumns="True"/>
this.dataGrid.GridCopyPaste = new CustomCopyPaste(dataGrid);
…….
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
//Creates the new list for add the selected records
public List<object> selectedItem = new List<object>();
protected override void PasteToRows(object clipboardRows)
{
base.PasteToRows(clipboardRows);
//Uses the SelectionController to apply the selection for Pasted records
this.dataGrid.SelectionController.HandleGridOperations(new GridOperationsHandlerArgs(GridOperation.Paste, selectedItem));
}
protected override void PasteToRow(object clipboardContent, object selectedRecords)
{
//Adds the selected record to list
selectedItem.Add(selectedRecords);
base.PasteToRow(clipboardContent, selectedRecords);
}
}
How to add the copied rows as new rows in the SfDataGrid while pasting
By default, while pasting, it changes the values of already existing records based on the clipboard content. The following code example shows how to add the copied records as new rows in the SfDataGrid by overriding the PasteToRows method in the GridCutCopyPaste class. Here, the new class CustomCopyPaste is created and assigned to the SfDataGrid.GridCopyPaste.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding Products}"
SelectionUnit="Row"
SelectionMode="Extended"
AutoGenerateColumns="True"/>
this.dataGrid.GridCopyPaste = new CustomCopyPaste(dataGrid);
…….
public class CustomCopyPaste : GridCutCopyPaste
{
public CustomCopyPaste(SfDataGrid dataGrid)
: base(dataGrid)
{
}
protected override void PasteToRows(object clipboardRows)
{
var copiedRecord = (string[])clipboardRows;
int copiedRecordsCount = copiedRecord.Count();
//Based on the clipboard count, the new record for paste is added
if (copiedRecordsCount > 0)
{
//Gets the view model for adding the record
var rec = this.dataGrid.DataContext as ViewModel;
for (int i = 0; i < copiedRecordsCount; i++)
{
//Creates the new instance for Model, for adding the new record
Product entity = new Product();
for (int j = 0; j < this.dataGrid.Columns.Count; j++)
{
var record = copiedRecord[i];
string[] recd = Regex.Split(record, @"\t");
//Adds the new record by using PasteToCell method by passing the created data, particular column, and clipboard value
this.PasteToCell(entity, this.dataGrid.Columns[j], recd[j]);
}
//Adds the pasted record in collection
rec.Products.Add(entity);
}
}
}
}
How To
What is the difference between CurrentItem and SelectedItem
This following table differentiates Grid CurrentItem and SelectedItem.
SelectionMode | CurrentItem | SelectedItem |
---|---|---|
Single | The row focused is the CurrentItem. | The row that is selected is the SelectedItem |
Multiple and Extend | The row focused is the CurrentItem and in navigation it travels from CurrentItem among the selected items. | The row is selected initially among the selected items. |
NOTE
In the Single mode, both the CurrentItem and SelectedItem properties have the same item. SfDataGrid Selected Items are collections of your selected records.
How to copy records without using mouse pointer
SfDataGrid supports copying records without using mouse to select the records and paste it to Excel, Notepad, and Word. You can make use of Copy (), Cut () and Paste () methods that are available in the GridCopyPaste class of the SfDataGrid. The following code example explains how to do it.
void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
//The following code example sets you a current record that is not selected by you.
RowColumnIndex rowColumnIndex = new RowColumnIndex();
rowColumnIndex.RowIndex = 2;
rowColumnIndex.ColumnIndex = 2;
this.dataGrid.SelectionController.MoveCurrentCell(rowColumnIndex);
//The following code copies the content for you without interaction to grid.
dataGrid.GridCopyPaste.Copy();
}
Add the above code example in an application. Now you can paste the content in another application. The same method is used for single file and Multiple Records.
How to scroll to SelectedIndex in SfDataGrid
SfDataGrid provides the method that scrolls to a particular record in ScrollInView (RowColumnIndex rowColumnIndex) where you can view the record that is not in View port. The following code example illustrates Pass row index as SelectedIndex and some appropriate value for ColumnIndex that is in view.
dataGrid.ScrollInView(new RowColumnIndex() { RowIndex = dataGrid.SelectedIndex=7, ColumnIndex = 1 });
This scrolls the SfDataGrid to the selected index of record.