Selection and Focus in Blazor Grid
- 12 minutes to read
Focused Row vs. Selection
Focused and selected rows have a lot in common. For example, you can allow users to focus a row and display/update additional information outside of the grid component. You can do the same with selected rows - whether you allow single or multiple selection. The key differences between the two features are outlined below:
- The focused row is a navigation feature, while selected rows facilitate operations on data rows. For example, if you navigate to a different page or filter the grid, focus can change. Row selection doesn’t change as a result of navigation or data shaping operations.
- Focused row appearance usually has more contrast compared to selected rows.
Selection in Blazor Grid
The DevExpress Blazor Grid supports single and multiple row selection. Users can click rows or use a specially-designed column to select/deselect records. You can also manage selection in code.
Note
Grid compares and identifies data items to ensure accurate selection operations. If your data object has a primary key, assign it to the KeyFieldName or KeyFieldNames property. Otherwise, the Grid uses standard .NET value equality comparison to identify data items.
Single Row Selection
The DevExpress Blazor Grid supports single and multiple (default) row selection. Set the SelectionMode property to Single
to allow only one row to be selected at a time.
<DxGrid Data="Products" KeyFieldName="ProductId" SelectionMode="GridSelectionMode.Single" >
<Columns> ... </Columns>
</DxGrid>
Tip
Use the row focus feature to navigate between grid records and perform actions related to the currently focused row.
Select Rows in the UI
The grid allows users to select rows in the following ways:
Row Click
Set the AllowSelectRowByClick property to true
to allow users to select rows by mouse clicks, tap gestures, and keyboard shortcuts.
<DxGrid Data="@Products"
KeyFieldName="ProductId"
AllowSelectRowByClick="true"
@bind-SelectedDataItems="@SelectedDataItems">
<Columns>...</Columns>
</DxGrid>
The following user operations are available:
Operation | Description |
---|---|
Click | Click a row to select it and clear the selection of all other rows. |
Ctrl+Click | Hold down the Ctrl key and click a row to add/remove the row to/from selection. |
Shift+Click | Click the first row in a range, hold down the Shift key, and click the last row in the range to select a range of rows. |
Ctrl+Shift+Click | Hold down the Ctrl key, click the first row in the range, hold down the Shift key, and click the last row in the range to add the range of rows to the selection. |
Space | Focus a cell in a row and press Space to select the row and clear the selection of all other rows. |
Tap | Tap a row to select it and clear the selection of all other rows. |
Long Tap | Tap a row for an extended period of time to add/remove the row to/from selection. |
Long Tap+Move | Tap a row for an extended period and move the finger to add a range of rows to the current selection. |
Selection Column
Declare a DxGridSelectionColumn object in the Columns template to display the selection column.
<DxGrid Data="Products" KeyFieldName="ProductId">
<Columns>
<DxGridSelectionColumn />
...
</Columns>
</DxGrid>
When the SelectionMode property is set to Multiple
(the default value), the selection column displays checkboxes. Users can click them to select and deselect individual rows.
In Multiple
selection mode, the selection column displays the Select All check box in the column header. A user can click this checkbox to select or deselect all rows on the current page or on all grid pages depending on the SelectAllCheckboxMode property value. Available property values are as follows:
- Page
- The Select All checkbox selects and deselects all rows on the current grid page. This mode changes to
Mixed
when the Grid is bound to a large data source and vertical virtual scrolling mode is activated. - AllPages
- The Select All checkbox selects and deselects all rows on all grid pages. This mode changes to
Mixed
when the Grid is bound to a large data source. - Mixed
- The Select All checkbox selects and deselects all rows on the current grid page. An additional drop-down button displays a context menu that allows users to select and deselect all rows on all grid pages.
<DxGrid Data="Products"
KeyFieldName="ProductId"
SelectAllCheckboxMode="GridSelectAllCheckboxMode.Mixed">
<Columns>...</Columns>
</DxGrid>
To hide the Select All check box, disable the column’s AllowSelectAll option.
Note
The Select All check box functionality has some limitations. To learn more, see the following section: Limitations.
When the SelectionMode property is set to Single
, the selection column displays radio buttons. Users can click a button to select one row at a time.
<DxGrid Data="Products" KeyFieldName="ProductId" SelectionMode="GridSelectionMode.Single">
<Columns>
<DxGridSelectionColumn />
...
</Columns>
</DxGrid>
You can use the FixedPosition property to freeze the selection column and keep it visible on screen while users scroll the grid horizontally.
Select and Deselect Rows in Code
Grid implements a number of Select* and Deselect* methods that allow you to change row selection in code. The table below lists these methods.
Select* Methods | Deselect* Methods | Description |
---|---|---|
SelectRow | DeselectRow | Sets selection state of a row with the specified visible index. |
SelectRows | DeselectRows | Sets selection state of rows with the specified visible indexes. |
SelectDataItem | DeselectDataItem | Sets selection state of a row that corresponds to the specified data item. |
SelectDataItems | DeselectDataItems | Sets selection state of rows that correspond to the specified data items. |
SelectAllOnPage | DeselectAllOnPage | Sets selection state of all rows on the current visible page. |
SelectAllAsync | DeselectAllAsync | Sets selection state of all rows in the grid. These methods do not affect the selection state of rows hidden by a filter. |
Call the ClearSelection() method to clear selection of all rows on all pages.
Obtain Selected Data Items
Single selection mode
Implement two-way binding for the SelectedDataItem property to access the data item that corresponds to the selected row. When a property value changes, the SelectedDataItemChanged event fires.
<DxGrid Data="Data" KeyFieldName="ProductId" AllowSelectRowByClick="true"
SelectionMode="GridSelectionMode.Single"
@bind-SelectedDataItem="@SelectedDataItem" >
<Columns> ... </Columns>
</DxGrid>
<div>
<p><b>Selected product:</b> @((SelectedDataItem as Product)?.ProductName ?? "(none)")</p>
</div>
@code {
object SelectedDataItem { get; set; }
// ...
}
Multiple selection mode
Implement two-way binding for the SelectedDataItems property to access data items that correspond to selected rows. When a property value changes, the SelectedDataItemsChanged event fires.
<DxGrid Data="Data" KeyFieldName="ProductId" AllowSelectRowByClick="true"
@bind-SelectedDataItems="@SelectedDataItems" >
<Columns> ... </Columns>
</DxGrid>
<div>
<b>Selected products:</b>
@foreach (var product in SelectedDataItems.Cast<Product>()) {
<li>@product.ProductName</li>
}
</div>
@code {
IReadOnlyList<object> SelectedDataItems { get; set; }
// ...
}
The SelectedDataItemsChanged event allows you to get data items that are added to and removed from selection. For this purpose, cast the event handler’s parameter to the IGridSelectionChanges interface. The SelectedDataItems and DeselectedDataItems properties return information about selection changes.
<DxGrid Data="Data" KeyFieldName="ProductId" AllowSelectRowByClick="true"
SelectedDataItems="@SelectedDataItems"
SelectedDataItemsChanged="OnSelectedDataItemsChanged">
<Columns> ... </Columns>
</DxGrid>
@code {
// ...
void OnSelectedDataItemsChanged(IReadOnlyList<object> newSelection) {
if (newSelection is IGridSelectionChanges changes) {
SelectedItemsInfo = string.Join("; ", changes.SelectedDataItems.Cast<Product>().Select(p => p.ProductName));
DeselectedItemsInfo = string.Join("; ", changes.DeselectedDataItems.Cast<Product>().Select(p => p.ProductName));
}
SelectedDataItems = newSelection;
}
}
Selection Limitations
- When the Grid component displays all items on one page (including virtual scrolling mode),
Page
andAllPages
modes function identically. - In virtual scrolling mode, the Grid component cannot determine the state of the Select All checkbox in
Mixed
mode. In such a case, the Grid sets the checkbox state to indeterminate state and displays the checkbox in read-only mode.
DevExpress Blazor Grid has the following specifics and limitations when you use a remote data source, such as Server Mode data source or GridDevExtremeDataSource:
The second call to SelectAllAsync and DeselectAllAsync method cancels the operation initiated by the previously called method.
SelectAllAsync and DeselectAllAsync methods load all data to the grid and can reduce overall performance and increase memory consumption.
If the SelectAllCheckboxMode property is set to
AllPages
, the DxGrid switches it toMixed
to improve performance.In virtual scrolling mode, the DxGrid sets the SelectAllCheckboxMode property to
Mixed
, sets the Select All checkbox state to indeterminate state and displays the checkbox in read-only mode.
Focused Row
Set the FocusedRowEnabled property to true
to allow users to focus individual grid rows. The focused row is always visible on the current grid page. If you change the current page, the focused row changes.
You can handle the FocusedRowChanged event to react to focus row change. In the following code snippet, this event is handled to display additional information about the focused employee.
<DxGrid Data="GridData" PageSize="5" FocusedRowEnabled="true" FocusedRowChanged="Grid_FocusedRowChanged">
<Columns> ... </Columns>
</DxGrid>
<DxFormLayout>
<DxFormLayoutItem Caption="@MemoCaption" CaptionPosition="CaptionPosition.Vertical"
Visible="@ShowMemo" ColSpanMd="12">
<DxMemo Text=@Notes Rows="4"/>
</DxFormLayoutItem>
</DxFormLayout>
@code {
string MemoCaption { get; set; }
string Notes { get; set; }
bool ShowMemo { get; set; }
void Grid_FocusedRowChanged(GridFocusedRowChangedEventArgs e) {
if(e.DataItem != null) {
ShowMemo = true;
var employee = (Employee)e.DataItem;
MemoCaption = employee.FirstName + " " + employee.LastName + " details:";
Notes = employee.Notes;
}
else {
ShowMemo = false;
}
}
object GridData { get; set; }
protected override async Task OnInitializedAsync() {
GridData = await NwindDataService.GetEmployeesAsync();
}
}
Related API
This section contain a comprehensive selection and focus-related API reference.
Grid API member | Type | Description |
---|---|---|
AllowSelectRowByClick | Property | Specifies whether users can select and deselect rows by mouse clicks, tap gestures, and keyboard shortcuts. |
SelectAllCheckboxMode | Property | Specifies whether the Select All checkbox selects all rows on the current page or on all grid pages. |
SelectionMode | Property | Specifies selection mode. |
SelectedDataItem | Property | In single selection mode, this property specifies the data item that corresponds to the selected Grid row. |
SelectedDataItems | Property | In multiple selection mode, this property specifies data items that corresponds to selected Grid rows. |
IsDataItemSelected(Object) | Method | Returns whether the row that corresponds to the specified data item is selected. |
IsRowSelected(Int32) | Method | Returns whether the specified row is selected. |
ClearSelection() | Method | Clears selection. |
DeselectAllAsync() | Method | Deselects all rows in the grid. |
DeselectAllOnPage() | Method | Deselects all rows on the current visible page. |
DeselectDataItem(Object) | Method | Deselects a row that corresponds to the specified data item. |
DeselectDataItems(IEnumerable<Object>) | Method | Deselects rows that correspond to the specified data items. |
DeselectRow(Int32) | Method | Deselects a row with the specified visible index. |
DeselectRows(IEnumerable<Int32>) | Method | Deselects rows with the specified visible indexes. |
SelectAllAsync(Boolean) | Method | Selects or deselects all rows in the grid. |
SelectAllOnPage(Boolean) | Method | Selects or deselects all rows on the current visible page. |
SelectDataItem(Object, Boolean) | Method | Selects or deselects a row that corresponds to the specified data item. |
SelectDataItems(IEnumerable<Object>, Boolean) | Method | Selects or deselects rows that correspond to the specified data items. |
SelectRow(Int32, Boolean) | Method | Selects or deselects a row with the specified visible index. |
SelectRows(IEnumerable<Int32>, Boolean) | Method | Selects or deselects rows with the specified visible indexes. |
SelectedDataItemChanged | Event | In single selection mode, fires when another Grid row is selected. |
SelectedDataItemsChanged | Event | In multiple selection mode, fires when the selection in the Grid changes. |
Selection Column API member | Type | Description |
---|---|---|
AllowSelectAll | Property | Specifies whether the selection column contains the Select All checkbox. |
CellDisplayTemplate | Property | Specifies a template for selection column cells. |
FilterRowCellTemplate | Property | Specifies a template for the selection column’s filter row cell. |
HeaderTemplate | Property | Specifies a template for the selection column header. |
Export API member | Type | Description |
---|---|---|
GridExportOptions.ExportSelectedRowsOnly | Property | Specifies if the grid exports only selected rows. |
Grid API member | Type | Description |
---|---|---|
FocusedRowEnabled | Property | Specifies whether the row focus is enabled. |
GetFocusedDataItem() | Method | Returns a data item bound to the focused data row. |
GetFocusedRowIndex() | Method | Returns the visible index of the focused row. |
IsDataItemFocused(Object) | Method | Identifies whether the row bound to the specified data item is focused. |
IsRowFocused(Int32) | Method | Identifies whether the row with the specified visible index is focused. |
SetFocusedDataItemAsync(Object) | Method | Moves focus to the row bound to the specified data item. |
SetFocusedRowIndex(Int32) | Method | Moves focus to the row with the specified visible index. |
FocusedRowChanged | Event | Fires when the row focus changes. |
GitHub Examples
- Delete Selected Rows
- Disable Selection Checkboxes in Specific Rows
- Select and Deselect All Rows in a Group
Online Demos
Task-Based Examples
This section contains code samples that demonstrate row selection functionality.
Scroll Grid to the Selected Data Item
Pass the SelectedDataItem object to the MakeDataItemVisibleAsync(Object) method to scroll data to the row bound to the specified data item.
Grid.MakeDataItemVisibleAsync(Grid.SelectedDataItem);
Limit the Number of Selected Rows
The SelectedDataItemsChanged event fires when the selection in the Grid changes. Handle this event to determine the number of selected rows and deselect them if the number of selected rows exceeds a predefined maximum value.
<DxGrid @ref=Grid Data="@forecasts"
SelectedDataItems="SelectedItems"
SelectedDataItemsChanged="Grid_SelectedDataItemsChanged">
<Columns>
<DxGridSelectionColumn />
<DxGridDataColumn FieldName="Date" />
<DxGridDataColumn FieldName="TemperatureF" />
</Columns>
</DxGrid>
@code {
int maxSelectedRowCount = 3;
private WeatherForecast[]? forecasts;
IReadOnlyList<object> SelectedItems;
IGrid Grid;
void Grid_SelectedDataItemsChanged(IReadOnlyList<object> newSelection) {
SelectedItems = newSelection;
if (newSelection?.Count > maxSelectedRowCount)
Grid.DeselectDataItems(newSelection.Skip(maxSelectedRowCount));
}
protected override async Task OnInitializedAsync() {
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
}
How to Get a Notification When the Select All Checkbox State Changes
There is no event to notify that the Select All checkbox is clicked. You can create your own template to reproduce the default render and observe the checkbox’s state.
<DxGrid Data="GridData">
<Columns>
<DxGridSelectionColumn>
<HeaderTemplate>
<DxCheckBox T="bool?"
Checked="context.Selected"
CheckedChanged="(newValue) => SelectAllCheckboxClicked(newValue, context)"/>
</HeaderTemplate>
</DxGridSelectionColumn>
<DxGridDataColumn FieldName="OrderID" />
<DxGridDataColumn FieldName="OrderDate" />
</Columns>
</DxGrid>
@code {
void SelectAllCheckboxClicked(bool? newValue, GridSelectionColumnHeaderTemplateContext context) {
context.Selected = newValue!.Value;
// .. your actions here
}
}
How to Suppress Row Selection When a Certain Element in Grid is Clicked
When the AllowSelectRowByClick property is set to true
, users can click rows to select them. If your grid contains links or custom buttons, a click on the element initiates the element-related action, then the RowClick event fires and the row is selected. Use the stopPropagation directive attribute to prevent the click from triggering Grid events. In this case, clicking these links or buttons does not cause row selection.
<DxGridDataColumn FieldName="TotalPrice" DisplayFormat="c" UnboundType="GridUnboundColumnType.Decimal">
<CellDisplayTemplate>
<a @onclick:stopPropagation @onclick="() => ShowDetails()">More Info</a>
@* or *@
<div @onclick:stopPropagation="true">
@* Custom buttons *@
</div>
</CellDisplayTemplate>
</DxGridDataColumn>
How to Use a Custom Checkbox Inside a Selection Column
To replace selection column editors with custom checkboxes, place the DxCheckBox<T> component in CellDisplayTemplate and implement two-way binding to bind the Checked checkbox property to the context.Selected value.
<DxGridSelectionColumn Width="104px">
<CellDisplayTemplate Context="SelContext">
<DxCheckBox @bind-Checked="SelContext.Selected" />
</CellDisplayTemplate>
</DxGridSelectionColumn>
Select Rows in a Group
To allow users to select and deselect all rows in a group, implement the DataColumnGroupRowTemplate template. Place the DxCheckBox<T> component in the template and handle checked state changes.
You can see a complete code sample in the following GitHub example: Select and Deselect All Rows in a Group