How to get information from the selected cells when using cell selection?
Cell selection, just like in Excel, can be enabled by setting SfDataGrid.SelectionUnit as Cell or Any. While selecting cells using cell selection, you can access the selected cells details using the SfDataGrid.GetSelectedCells method. It returns the collection of GridCellInfo.
Here, SfDataGrid is defined with cell selection by setting SelectionUnit as Cell.
XAML
<syncfusion:SfDataGrid x:Name="sfdatagrid" AllowSorting="True" Grid.Column="0" SelectionUnit="Cell" SelectionMode="Multiple" ItemsSource="{Binding Path=Products}"> </syncfusion:SfDataGrid> <StackPanel Grid.Column="1"> <Button Click="Button_Click" Content="SelectedItems"/> </StackPanel>
The following code example explains how you can get the selected cells’ information using SfDataGrid.GetSelectedCells method.
C#
using Syncfusion.UI.Xaml.Grid; private void Button_Click(object sender, RoutedEventArgs e) { int rowindex = 0; //Get selectd cells data var selectedcells = this.sfdatagrid.GetSelectedCells(); //calculate the total number of selected cell in SfDataGrid int count = selectedcells.Count; for (int i = 0; i < count; i++) { GridCellInfo cellinfo = selectedcells[i]; //Get selected cell row index if (!cellinfo.IsDataRowCell) continue; rowindex = this.sfdatagrid.ResolveToRowIndex(cellinfo.RowData); var gridColumnIndex = this.sfdatagrid.Columns.IndexOf(cellinfo.Column); //Resolve the column index var visibleColumnIndex = this.sfdatagrid.ResolveToGridVisibleColumnIndex(gridColumnIndex); //Get the SelectedCell values var propertyCollection = this.sfdatagrid.View.GetPropertyAccessProvider(); var cellvalue = propertyCollection.GetValue(cellinfo.RowData, cellinfo.Column.MappingName); } }
The GridCellInfo class contains the following properties:
RowData- Gets or sets record information of the row.
RowIndex- Gets row index of the selected cell.
Column- Gets or sets the column of the selected cell.
IsDataRowCell- Gets a value indicating whether the selected cell is a data row cell.
IsAddNewRow- Gets a value indicating whether the selected cell is in AddNewRow.
You can use the following helpers to extract information from GridCellInfo:
GridIndexResolver.ResolveToRowIndex- You can use this method to get RowIndex from the Record, GridCellInfo.RowData.
GridIndexResolver.ResolveToRecordIndex- You can use this method to get Record index from the RowIndex, GridCellInfo.RowIndex.
GridIndexResolver.ResolveToGridVisibleColumnIndex- You can use this method to get the visiblecolumn index from the GridColumn index.
SfDataGrid.View.GetPropertyAccessProvider- This method returns IPropertyAccessProvider, that is used to reflect values by passing value and property name.
Refer the following screenshot to get the information of selected cell value.
Sample Links: