Selection in Xamarin DataGrid (SfDataGrid)

This section explains how to enable selection in the data grid; modes, properties, and events involved in selection; and customizations available for selection.

The data grid allows you to select a specific row or group of rows either programmatically or by touch interactions. To enable selection, set the SfDataGrid.SelectionMode property to a value other than None. This control has different selection modes to perform the selection operation as follows:

Disable selection for rows and columns

You can disable selection and navigation in a particular column using the GridColumn.AllowFocus property. You can disable selection in a particular row or cell or column by handling the CurrentCellActivating event.

NOTE

It is not possible to select header rows, table summary rows, and unbound rows that are above the table summary row when they are placed at the top and the unbound rows that are placed are below table summary rows when they placed at the bottom of SfDataGrid.

Selection in Xamarin DataGrid (SfDataGrid) modes

Modes Description

None

Disables selection, and no rows can be selected. This is the default value.

Single

Allows selection of a single row only. Upon selecting the next row, the selection in the previous row is cleared.

Multiple

Allows selection of more than one row. Selection is not cleared when selecting more than one record. When you click on a selected row for the second time, the selection is cleared.

SingleDeselect

Allows selection of only a single row. However, upon tapping the row again, the selection is cleared. Similar to single mode, upon selecting the next row, the selection in the previous row is cleared.

To set the selection mode, follow the code example:

<syncfusion:SfDataGrid x:Name="dataGrid"
                       ColumnSizer="Star"
                       AutoGenerateColumns="True"
                       SelectionMode="Multiple" 
                       ItemsSource="{Binding OrdersInfo}"/>
dataGrid.SelectionMode = SelectionMode.Multiple;

DataGrid with multiple selection

Getting selected rows

The SfDataGrid provides SelectedIndex, SelectedItem, and CurrentItem properties to get details of the selected rows when the selection mode is Single, Multiple, and SingleDeselect.

  • SfDataGrid.SelectedItem: Provides the underlying data object of the selected row. Denotes the first selected row in multiple selection.
  • SfDataGrid.SelectedIndex: Provides the index of SfDataGrid.SelectedItem.
  • SfDataGrid.CurrentItem: Provides the underlying data object of the currently selected row in the data grid. Denotes the first selected row in multiple selection.

Row selection

When multiple rows are selected, the SelectedItems and SelectionController.SelectedRows properties provide information of all the selected rows.

CurrentItem vs SelectedItem

Both the SelectedItem and CurrentItem returns the same data object when the selection mode is single. When multiple selection is enabled, the initially selected row will be maintained in the SelectedItem and the currently selected row will be maintained in the CurrentItem.

Programmatic selection

When SfDataGrid.SelectionMode is set a value other than None, select row/rows from the code by setting the SfDataGrid.SelectedIndex, SfDataGrid.SelectedItem, or SfDataGrid.SelectedItems property based on the selection mode. To enable selection from code, follow the code example:

When the selection mode is Single, programmatically select a row in two ways either by setting the row index to the SfDataGrid.SelectedIndex property, or by setting the underlying object to be selected to the SfDataGrid.SelectedItem property.

To programmatically select a row from the code, follow the code example:

//Perform selection using selected index
dataGrid.SelectedIndex = 3;
 
//Perform selection using selected item
dataGrid.SelectedItem = viewModel.OrdersInfo [5];

When the selection mode is multiple, programmatically select more than one row by adding the underlying object to be selected to the SfDataGrid.SelectedItems property.

To programmatically select more than one row from the code, follow the code example:

//Perform multiple selection using selected item
dataGrid.SelectedItems.Add (viewModel.OrdersInfo [4]);
dataGrid.SelectedItems.Add (viewModel.OrdersInfo [6]);
dataGrid.SelectedItems.Add (viewModel.OrdersInfo [9]);
dataGrid.SelectedItems.Add (viewModel.OrdersInfo [11]);

The following screenshot shows the selection functionality in the data grid:

DataGrid with multiple selection

Keyboard behavior

SfDataGrid supports selection via keyboard interaction for the Xamarin.Forms.macOS and Xamarin.Forms.UWP platforms. Keyboard interaction will not have any effect when the SfDataGrid.SelectionMode is set as SelectionMode.None.

Key or key combinations Description
DownArrow Moves selection to the next row directly below the currently selected row when the SelectionMode is Single. Upon reaching the bottom of screen, pressing down arrow scrolls and applies selection to the next row if grid has scrollable content. If the selected row is the last row of grid, pressing down arrow does nothing. In `Multiple` and `SingleDeselect` selection modes, if the next row has already been selected, pressing down arrow key will deselect the row.
UpArrow Moves selection to the previous row directly above the currently selected row when the SelectionMode is Single. Upon reaching the top of screen, pressing up arrow scrolls and applies selection to the previous row if grid has scrollable content. If the selected row is the first row of grid, pressing up arrow does nothing. In `Multiple` and `SingleDeselect` selection modes, if the previous row has already been selected, pressing up arrow key will deselect the row.
PageDown SfDataGrid will be scrolled to the next set of rows that are not displayed in view including the partially displayed row. If selection is applied to any row, pressing PageDown arrow will move selection to the last row of the next set of rows when the SelectionMode is Single.
PageUp SfDataGrid will be scrolled to the previous set of rows that are not displayed in view including the partially displayed row. If the selection is applied to any row, pressing PageUp will move selection to the first row of the next set of rows when the SelectionMode is Single.
Tab Moves selection to the next row directly below the currently selected row when the SelectionMode is Single. Upon reaching the bottom of screen, pressing Tab key scrolls and applies selection to the next row if grid has scrollable content. If the selected row is the last row of grid, pressing Tab key does nothing. In `Multiple` and `SingleDeselect` selection modes, if the next row has already been selected, pressing Tab key will deselect the row.
Ctrl + Home or Ctrl + UpArrow or Home Scrolls grid to the first row of the collection.
Ctrl + End or Ctrl + DownArrow or End Scrolls grid to the last row of the collection.
Enter or Ctrl + Enter If the active current cell is in edit mode, changes will be committed and selection will be moved to the row below the active current cell. If the active current cell is in last row, commits changes and only editing is ended.
Esc If the current cell is in edit mode, reverts the changes done in the current cell. If the underlying source implements the

IEditableObject

, pressing Esc key for the second time will cancel the edit mode for the entire row.
Delete Deletes all the rows that are currently in selection. To prevent rows from being deleted set the [SfDataGrid.AllowDeleting](https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataGrid.XForms~Syncfusion.SfDataGrid.XForms.SfDataGrid~AllowDeleting.html) as `False`.

Shift key combinations

Key combinations Description
Shift + DownArrow If the Selection Mode is multiple, the next multiple rows will be continuously selected below the currently selected row. If the Selection Mode is Single or SingleDeselect, selection will be moved to the next row.
Shift + UpArrow If the Selection Mode is multiple, the previous multiple rows will be continuously selected above the currently selected row. If the Selection Mode is Single or SingleDeselect, selection will be moved to the previous row.
Shift + Tab Moves selection to the previous row from the currently selected row when the SelectionMode is Single or SingleDeselect. If the selected row is in first row, pressing Shift +Tab does nothing.

Customize key functionalities

To perform custom actions apart from the functionalities mentioned in the above tables for key press actions of the keyboard, implement your custom actions in the ProcessKeyDown() override of the custom written selection controller class derived from GridSelectionController and assign it to the SfDataGrid.GridSelectionController property.

<ContentPage.Resources>
        <local:CustomSelectionController x:Key="CustomSelectionController" />
</ContentPage.Resources>

  <syncfusion:SfDataGrid x:Name="dataGrid"
                          ItemsSource="{Binding OrdersInfo,Mode=TwoWay}"
                          AllowEditing="True"
                          NavigationMode="Cell"
                          SelectionMode="Single"
                          SelectionController="{x:StaticResource CustomSelectionController}">
    </syncfusion:SfDataGrid>
dataGrid.SelectionController = new CustomSelectionController();
public class CustomSelectionController : GridSelectionController
    {
        public CustomSelectionController()
        {
           this.SelectedRows = new GridSelectedRowsCollection();
        }

        protected override void ProcessKeyDown(string keyCode, bool isCtrlKeyPressed, bool isShiftKeyPressed)
        {
            if(keyCode == "Down")
            {
                // your logics here
            }
            else
            {
                // default key action
                base.ProcessKeyDown(keyCode, isCtrlKeyPressed, isShiftKeyPressed);
            }
        }
    }

Scroll to selected item

You can scroll programmatically to the selected item by passing the SelectedIndex to the SfDataGrid.ScrollToRowIndex method.

dataGrid.ScrollToRowIndex((int)dataGrid.SelectedIndex);

Clear selection

Data grid allows you to clear the selection applied in the grid rows either by setting the SfDataGrid.SelectionMode to None or by calling the SfDataGrid.SelectionController.ClearSelection () method.

//Clear selection using selection mode
dataGrid.SelectionMode = SelectionMode.None;

//Clear selection using selection controller
dataGrid.SelectionController.ClearSelection ();

NOTE

Selected items and selections will be cleared whenever the ItemsSource is changed at runtime.

Row header selection

Data grid allows you to select the grid row(s) upon tapping them over the grid cells. It also allows you to select the grid rows when you tap the row header cells. To enable selection in the data grid, set the SfDataGrid.SelectionMode property to a value other than None.

Select records in the data grid when tapping only on the row header cells

The data grid allows you to select a specific row or group of rows by touching the grid cells. However, to select the record only when tapping the row header cells, use the SfDataGrid.SelectionChanging event.

dataGrid.SelectionMode = SelectionMode.Single;

private void DataGrid_SelectionChanging(object sender, GridSelectionChangingEventArgs e)
{
    e.Cancel = true;
}

private void DataGrid_GridTapped(object sender, GridTappedEventsArgs e)
{
    if(e.RowColumnIndex.ColumnIndex == 0)
    {
        dataGrid.SelectedIndex = e.RowColumnIndex.RowIndex;
    }
}

NOTE

To enable the row header in the data grid, set the SfDataGrid.ShowRowHeader to true.

Selection in Xamarin DataGrid (SfDataGrid) animation

The data grid supports selecting one or more rows programmatically or by touch interactions. In addition, the control also provides extensibility to animate the selected rows.

It can be done by extending the GridSelectionController.

Refer to the following example in which a CustomSelectionController is derived from GridSelectionController and an instance of it is assigned to the SfDataGrid.SelectionController property to perform selection animation.

<ContentPage.Resources>
    <ResourceDictionary>
        <local:CustomSelectionController x:Key="CustomSelectionController" DataGrid="{x:Reference dataGrid}">
        </local:CustomSelectionController>
    </ResourceDictionary>
</ContentPage.Resources>

<ContentPage.Content>
    <sfgrid:SfDataGrid x:Name="dataGrid"
            ColumnSizer="Star"
            SelectedIndex="1"
            SelectionMode="Multiple"
            VerticalOverScrollMode="None"
            SelectionController="{StaticResource CustomSelectionController}" />
</ContentPage.Content>
this.dataGrid.ItemsSource = viewModel.OrdersInfo;
this.dataGrid.SelectionController = new CustomSelectionController();
this.dataGrid.SelectionMode = SelectionMode.Multiple;
SelectionPicker.SelectedIndex = 1;
public class CustomSelectionController : GridSelectionController
{
    public CustomSelectionController()
    {
        this.SelectedRows = new GridSelectedRowsCollection();
    }
    protected override async void SetSelectionAnimation(VirtualizingCellsControl rowElement)
    {
        rowElement.Opacity = 0.50;
        await rowElement.FadeTo(1, 400, Easing.CubicInOut);
    }
}

DataGrid with selection animation

Events in selection

The data grid provides the following events for selection:

  • SelectionChanging: This event is raised while selecting a row at the execution time before the row is selected. So it allows canceling the selection action by setting the Cancel property of GridSelectionChangingEventArgs.
  • SelectionChanged: This event is raised after the column is selected.

These two events are triggered with GridSelectionChangingEventArgs and GridSelectionChangedEventArgs that contain the following properties:

  • AddedItems: Gets collection of the underlying data objects added for selection.
  • RemovedItems: Gets collection of the underlying data objects removed from selection.

To hook the SelectionChanging event and cancel the selection of a column, follow the code example:

dataGrid.SelectionChanging += DataGrid_SelectionChanging;  

void DataGrid_SelectionChanging (object sender, GridSelectionChangingEventArgs e)
{
    e.Cancel = true;
}

To get the selected item in code-behind using the SelectionChanged event, follow the code example:

dataGrid.SelectionChanged += DataGrid_SelectionChanged;

private void DataGrid_SelectionChanged (object sender, GridSelectionChangedEventArgs e)
{
    // Gets the selected item 
    var selectedItem = e.AddedItems[0];
}

CurrentItem

The SfDataGrid.CurrentItem property holds the underlying data of the last selected row in data grid.

Get the current item in the SfDataGrid.SelectionChanged event by setting the SfDataGrid.SelectionMode as Multiple or SingleDeselect. If the SelectionMode is Single, the current item and selected item are same.

dataGrid.SelectionMode = SelectionMode.Multiple; 
 
dataGrid.SelectionChanged += DataGrid_SelectionChanged; 
 
void DataGrid_SelectionChanged (object sender, GridSelectionChangedEventArgs e) 
{ 
 var currentItem = dataGrid.CurrentItem; 

 //your codes
}

Customizing Selection Appearance

Adding multiple selection color

The data grid supports selecting one or more rows either programmatically or by touch interactions. By default, the control applies a common background color for the selected rows based on the current theme. However, it also provides extensibility to have multiple selection colors when touching the rows by writing a custom SelectionController derived from GridSelectionController property. Override the GetSelectionColor() method to apply different colors for selection at runtime.

To set different colors for the selected rows in the data grid, follow the code example:

sfGrid.SelectionController = new CustomSelectionController(sfGrid);
sfGrid.SelectionMode = SelectionMode.Multiple;
public class CustomSelectionController : GridSelectionController
{
    public Color[] SelectionColors { get; set; }

    public CustomSelectionController(SfDataGrid datagrid) : base(datagrid)
    {
        this.DataGrid = datagrid;
        SelectionColors = new Color[11] 
        { 
            Color.DarkSalmon,
            Color.DarkSlateGray,
            Color.Red, 
            Color.Blue,
            Color.DarkOliveGreen, 
            Color.Black, 
            Color.Gray, 
            Color.MediumPurple,
            Color.BurlyWood,
            Color.DarkCyan,
            Color.DarkGoldenrod 
        };   
    }
    //Code to set multiple selection colors
    public override Color GetSelectionColor(int rowIndex, object rowData)
    {
        if (SelectionColors != null)
            return SelectionColors[rowIndex % 11];
        else
            return Color.Blue;
    }
}

The following screenshot shows the final outcome upon execution of the above code:

DataGrid with multiple selection colors

Changing selection background and foreground color

The SfDataGrid allows you to change the selection background and foreground colors by returning the required color in the GetSelectionBackgroundColor and GetSelectionForegroundColor properties overrides in the custom style class overriding from DataGridStyle and assign it to the SfDataGrid.GridStyle property.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sfgrid="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
             xmlns:local="clr-namespace:SummaryDemo"
             x:Class="SummaryDemo.Summary">

   <ContentPage.Resources>
        <ResourceDictionary>
            <local:SelectionStyle x:Key="selectionStyle"/>
        </ResourceDictionary>
    </ContentPage.Resources>

    <sfgrid:SfDataGrid x:Name="dataGrid"
                GridStyle="{StaticResource selectionStyle}"
                ItemsSource="{Binding OrdersInfo}" />
</ContentPage> 
//Apply selection background and foreground color to SfDataGrid from code.
SfDataGrid dataGrid = new SfDataGrid();
dataGrid.GridStyle = new SelectionStyle();
//Custom style class
public class SelectionStyle : DataGridStyle
    {
        public SelectionStyle()
        {         
        } 

        public override Color GetSelectionBackgroundColor()
        {
            return Color.Blue;
        }

        public override Color GetSelectionForegroundColor()
        {
            return Color.White;
        }
    }

DataGrid with custom selection background

Changing current cell border color

The SfDataGrid allows you to change the current cell border color applied to the grid cells when entering the edit mode by returning the required color in the GetCurrentCellBorderColor override of your custom style class derived from DataGridStyle and assign it to the SfDataGrid.GridStyle property.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sfgrid="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
             xmlns:local="clr-namespace:SummaryDemo"
             x:Class="SummaryDemo.Summary">

   <ContentPage.Resources>
        <ResourceDictionary>
            <local:SelectionStyle x:Key="selectionStyle"/>
        </ResourceDictionary>
    </ContentPage.Resources>

    <sfgrid:SfDataGrid x:Name="dataGrid"
                GridStyle="{StaticResource selectionStyle}"
                ItemsSource="{Binding OrdersInfo}" />
</ContentPage> 
//Apply selection background and foreground color to SfDataGrid from code.
SfDataGrid dataGrid = new SfDataGrid();
dataGrid.GridStyle = new SelectionStyle();
//Custom style class
public class SelectionStyle : DataGridStyle
    {
        public SelectionStyle()
        {         
        } 

        public override Color GetCurrentCellBorderColor()
        {
            return Color.Pink;
        }
    }

DataGrid with custom current cell border color

Binding selection properties

The SfDataGrid allows you to bind the selection properties such as SelectedIndex and SelectedItem to the properties in the ViewModel directly.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sfgrid="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
             xmlns:local="clr-namespace:SummaryDemo"
             x:Class="SummaryDemo.Summary">

    <ContentPage.BindingContext>
        <local:ViewModel x:Name="viewModel" />
    </ContentPage.BindingContext>

 <sfgrid:SfDataGrid x:Name="dataGrid"
                ItemsSource ="{Binding OrdersInfo}" 
                SelectionMode ="Multiple"
                SelectedIndex ="{Binding DataGridSelectedIndex,Mode=TwoWay}"
                SelectedItem ="{Binding DataGridSelectedItem,Mode=TwoWay}"/>
// In ViewModel.cs
          private int dataGridSelectedIndex;

          private object dataGridSelectedItem;

           public int DataGridSelectedIndex
        {
            get
            {
                return dataGridSelectedIndex;
            }
            set
            {
                this.dataGridSelectedIndex = value;
                RaisePropertyChanged("DataGridSelectedIndex");
            }
        }

        public object DataGridSelectedItem
        {
            get
            {
                return dataGridSelectedItem;
            }
            set
            {
                this.dataGridSelectedItem = value;
                RaisePropertyChanged("DataGridSelectedItem");
            }
        }

        public ViewModel()
        {
            DataGridSelectedIndex = 2;
            DataGridSelectedItem = OrdersInfo[5];
        }