Migrate from Data Grid to Grid
- 23 minutes to read
Why Are There Two Grid Components?
We released a new Grid component to replace the Data Grid component.
Important
The Data Grid was moved to maintenance support mode. No new features/capabilities will be added to this component.
Feature Comparison
The following table compares the two components. Note that we continue to add functionality to the new component. We plan to replicate all the functionality available in the older control.
Bind to Data | New Grid | Data Grid |
---|---|---|
Bind to Data Synchronously | ||
Bind to Data Asynchronously | ||
Large Datasets | ||
Large Datasets from an HTTP Service | ||
Unbound Columns | ||
Columns | New Grid | Data Grid |
Data Columns | ||
Command Column | ||
Reorder Columns | ||
Resize Columns | ||
Fit Column Widths to Their Content | ||
Column Chooser | ||
Edit Data | New Grid | Data Grid |
Edit Data | ||
Validate Input | ||
Shape Data | New Grid | Data Grid |
Sort Data by Value | ||
Sort Data by Display Text | ||
Custom Sorting | ||
Group Data | ||
Interval Grouping | ||
Custom Grouping | ||
Total and Group Summary | ||
Custom Total and Group Summary | ||
Filter Row | ||
Search Box | ||
Filter Menu | ||
Batch Modifications | ||
Selection and Navigation | New Grid | Data Grid |
Row Selection | ||
Paging | ||
Vertical Scrolling | ||
Horizontal Scrolling | ||
Fixed Columns | ||
Virtual Scrolling | ||
Handle a Row Click | ||
Appearance | New Grid | Data Grid |
Theme Support | ||
Custom Display Text | ||
Grid Header Template | ||
Column Header Caption Template | ||
Column Cell Display Template | ||
Column Footer Template | ||
Column Group Row Template | ||
Column Group Footer Template | ||
Empty Data Area Template | ||
Row Preview | ||
HTML Decoration | ||
Hierarchy and Layout | New Grid | Data Grid |
Master-Detail | ||
Save and Load Layout | ||
Tools | New Grid | Data Grid |
Toolbar | ||
Export | New Grid | Data Grid |
Export | ||
Keyboard Support | New Grid | Data Grid |
Keyboard Support |
Component Name
Update the component name from DxDataGrid to DxGrid.
<DxDataGrid>
@*...*@
</DxDataGrid>
<DxGrid>
@*...*@
</DxGrid>
Bind to Data Synchronously
You do not need to update your code if you bind the Data Grid to a data collection available during synchronous component initialization. The Data Grid includes the DxDataGrid.Data property for synchronous data binding. The new Grid contains the property with the same name: DxGrid.Data.
<DxDataGrid Data="@Data">
@*...*@
</DxDataGrid>
@code {
IEnumerable<WeatherForecast> Data;
// ...
protected override void OnInitialized() {
Data = GetForecast();
}
}
<DxGrid Data="@Data">
@*...*@
</DxGrid>
@code {
IEnumerable<WeatherForecast> Data;
// ...
protected override void OnInitialized() {
Data = GetForecast();
}
}
Bind to Data Asynchronously
Data Grid
The Data Grid includes the DxDataGrid.DataAsync property for asynchronous data binding. This property specifies an asynchronous function that returns a Task<IEnumerable<T>>
object and accepts a CancellationToken object as a parameter.
@using System.Threading
<DxDataGrid DataAsync="@LoadDataAsync">
@*...*@
</DxDataGrid>
@code {
async Task<IEnumerable<WeatherForecast>> LoadDataAsync(CancellationToken token) {
return await WeatherForecastService.GetForecastAsync();
}
}
Grid
The new Grid has no equivalent for the DataAsync
property, but you can use the DxGrid.Data parameter instead.
- Bind the
Data
parameter to a model field or property. - Initialize this field or property with data in the OnInitializeAsync lifecycle method (use the await operator).
<DxGrid Data="@Data">
@*...*@
</DxGrid>
@code {
object Data { get; set; }
protected override async Task OnInitializedAsync() {
Data = await WeatherForecastService.GetForecastAsync();
}
}
Large Datasets
Data Grid
The Data Grid can detect an IQueryable collection when you use data binding properties (DxDataGrid.Data, DxDataGrid.DataAsync, or DxDataGrid.CustomData). The Data Grid uses benefits of the corresponding LINQ query providers (such as Entity Framework).
Grid
The Grid supports the following data source types designed to work with large data collections:
- Server Mode Data Sources (Blazor Server only)
When you use these data sources, the Grid loads data in small portions on demand (instead of the entire dataset). This helps reduce memory consumption. All data shaping operations are delegated to underlying services (such as EF Core, XPO, and so on). These services process operations more efficiently and enhance overall performance.
The Grid includes synchronous Server Mode Data Sources (they lock the UI while data is retrieved) and asynchronous Instant Feedback Sources (they load data in a background thread and do not freeze the UI).
Data Access Technology
Server Mode Data Source
Instant Feedback Data Source
For more information and examples, refer to the following help topic: Large Data (Server Mode Sources).
- GridDevExtremeDataSource (Blazor Server and Blazor WebAssembly)
This data source allows you to bind the Grid to a large IQueryable data collection. The data source implementation is based on the DevExpress DevExtreme.AspNet.Data library.
When you use this data source, the Grid delegates data processing operations to an underlying query provider (such as LINQ to Objects, EF Core, and so on). The Grid loads only data required for the screen display. This helps enhance overall performance and application responsiveness, and reduces memory consumption.
For more information and examples, refer to the following help topic: Large Data (Queryable Collections).
Large Datasets from HTTP Services
Data Grid
To bind the Data Grid to a large dataset published as an HTTP service, do the following:
- Create an asynchronous DxDataGrid.CustomData delegate that processes data load options and sends HTTP requests to the specified URI.
- On the service side, implement an API controller and create action methods that use the DevExtreme.AspNet.Data library to return the result.
<DxDataGrid T="@WebApiOrder" CustomData="@LoadOrderData">
@*...*@
</DxDataGrid>
@code {
[Inject] protected HttpClient Client { get; set; }
protected async Task<LoadResult> LoadOrderData(DataSourceLoadOptionsBase options,
CancellationToken cancellationToken)
=> await LoadCustomData("https://js.devexpress.com/Demos/NetCore/api/DataGridWebApi/Orders",
options, cancellationToken);
protected async Task<LoadResult> LoadCustomData(string dataEndpointUri,
DataSourceLoadOptionsBase options, CancellationToken cancellationToken) {
using var response = await Client.GetAsync(options.ConvertToGetRequestUri(dataEndpointUri),
cancellationToken);
response.EnsureSuccessStatusCode();
using var responseStream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<LoadResult>(responseStream,
cancellationToken: cancellationToken);
}
}
Grid
When you migrate to the Grid, you do not need to change the API controller on the service side.
To load data from this service, use the GridDevExtremeDataSource<T> as follows:
- Create a
GridDevExtremeDataSource
class instance and pass a URL to the service as the constructor parameter. - Bind this instance to the DxGrid.Data parameter.
For more information, refer to the following help topic: Queryable Collections as HTTP Services.
<DxGrid Data="@Data">
@*...*@
</DxGrid>
@code {
[Inject] protected HttpClient Client { get; set; }
object Data { get; set; }
protected override async Task OnInitializedAsync() {
Data = new GridDevExtremeDataSource<WebApiOrder>(HttpClient,
"https://js.devexpress.com/Demos/NetCore/api/DataGridWebApi/Orders");
}
}
Columns
Declaration
Data Grid
You can specify columns directly between the <DxDataGrid>
and </DxDataGrid>
tags. If you define templates (for instance, EditFormTemplate or DetailRowTemplate), you should use the DxDataGrid.Columns property to add columns.
<DxDataGrid Data="@Data">
<DxDataGridColumn ... />
<DxDataGridSpinEditColumn ... />
@*...*@
</DxDataGrid>
Grid
Always use the DxGrid.Columns property to declare columns.
<DxGrid Data="@Data">
<Columns>
<DxGridDataColumn ... />
<DxGridDataColumn ... />
@*...*@
</Columns>
</DxGrid>
Column Types
The Data Grid ships with multiple predefined data column types that correspond to commonly used data types. The new Grid includes a single class for all data types (DxGridDataColumn).
Both the Data Grid and new Grid support a command column and selection column.
The following table explains how to update columns when you migrate to the new Grid:
Data Grid | New Grid |
---|---|
Use the DxGridDataColumn instead. | |
Use the DxGridDataColumn instead. | |
Use the DxGridDataColumn instead. | |
Use the DxGridDataColumn instead. Make sure that its editor is a combo box. Refer to the following topic for more information: Change a Column Editor to Combo Box. | |
Use the DxGridDataColumn instead. Make sure that its editor is a checkbox. Refer to the following topic for more information: Change a Column Editor to Checkbox. | |
Use the DxGridCommandColumn instead. | |
Use the DxGridSelectionColumn instead. |
Main Column Properties
The table below maps column properties available in the Data Grid and Grid components.
Data Grid | New Grid |
---|---|
DisplayFormat or CustomizeCellDisplayText event | |
Editing-related properties | - |
Sorting-related properties | See Sort Data |
Grouping-related properties | See Group Data |
<DxDataGrid Data="@Data">
<DxDataGridCommandColumn />
<DxDataGridSelectionColumn />
<DxDataGridDateEditColumn Field="Date" DisplayFormat="D" />
<DxDataGridSpinEditColumn Field="TemperatureC" Caption="@("Temp. (\x2103)")" Width="120px"
TextAlignment="DataGridTextAlign.Left" />
@*...*@
</DxDataGrid>
<DxGrid Data="@Data">
<Columns>
<DxGridCommandColumn />
<DxGridSelectionColumn />
<DxGridDataColumn FieldName="Date" DisplayFormat="D" />
<DxGridDataColumn FieldName="TemperatureC" Caption="@("Temp. (\x2103)")" Width="120px"
TextAlignment="GridTextAlignment.Left" />
@*...*@
</Columns>
</DxGrid>
Resize Columns
Data Grid
Use the ColumnResizeMode property to specify whether and how users can resize Data Grid columns. The DataGridColumnResizeMode enumeration lists all supported resize modes.
<DxDataGrid DataAsync="@CustomersService.Load"
...
ColumnResizeMode="DataGridColumnResizeMode.NextColumn">
@*...*@
</DxDataGrid>
Grid
Use the ColumnResizeMode property to specify whether and how users can resize Grid columns. The GridColumnResizeMode enumeration lists all supported resize modes.
<DxGrid Data="@Data"
...
ColumnResizeMode="GridColumnResizeMode.NextColumn">
@*...*@
</DxGrid>
Call the AutoFitColumnWidths() method to adjust column widths to their content (that is, cell content of visible columns, headers, and summaries).
Column Chooser
Both the Data Grid and new Grid can display the Column Chooser, which allows users to show, hide, and reorder columns.
Data Grid
The Column Chooser displays only data columns. Command and selection columns are not listed.
You can add the Column Chooser to the Data Grid’s toolbar:
- Add HeaderTemplate to the Data Grid’s markup.
- Add the DxDataGridColumnChooserToolbarItem item to the Toolbar component in this template.
<DxDataGrid Data="@Data">
<HeaderTemplate>
<DxToolbar>
<DxDataGridColumnChooserToolbarItem Alignment="ToolbarItemAlignment.Right" />
</DxToolbar>
</HeaderTemplate>
<Columns>
@*...*@
</Columns>
</DxDataGrid>
Grid
The Column Chooser displays data, command, and selection columns.
You can invoke the Column Chooser from any place in a .razor
file. To do this, use the ShowColumnChooser(String) method.
<DxButton Text="Column Chooser"
RenderStyle="ButtonRenderStyle.Secondary"
CssClass="column-chooser-button"
Click="OnClick" />
<DxGrid Data="@Data" @ref="Grid">
<Columns>
@*...*@
</Columns>
</DxGrid>
@code {
// ...
DxGrid Grid { get; set; }
void OnClick() {
Grid.ShowColumnChooser(".column-chooser-button");
}
}
Sort Data
The Data Grid and new Grid include similar sorting-related API. You only need to replace the DataGridColumnSortOrder enumeration with the GridColumnSortOrder enumeration for the SortOrder
property.
Data Grid | New Grid |
---|---|
(Accepts DataGridColumnSortOrder enum values) |
(Accepts GridColumnSortOrder enum values) |
<DxDataGrid Data="@Data" AllowSort="false">
<DxDataGridDateEditColumn Field="Date" DisplayFormat="D"
AllowSort="true"
SortOrder="DataGridColumnSortOrder.Descending"
SortIndex="0" />
@*...*@
</DxDataGrid>
<DxGrid Data="@Data" AllowSort="false">
<Columns>
<DxGridDataColumn FieldName="Date" DisplayFormat="D"
AllowSort="true"
SortOrder="GridColumnSortOrder.Descending"
SortIndex="0" />
@*...*@
</Columns>
</DxGrid>
Group Data
If you disable grouping in the entire Grid, replace the DxDataGrid.AllowColumnDragDrop property with the DxGrid.AllowGroup property. Use other grouping-related API without changes.
Data Grid | New Grid |
---|---|
<DxDataGrid Data="@Data"
AllowColumnDragDrop="false"
ShowGroupPanel="true">
<DxDataGridDateEditColumn Field="Date" DisplayFormat="D"
AllowGroup="true"
GroupIndex="0" />
@*...*@
</DxDataGrid>
<DxGrid Data="@Data"
AllowGroup="false"
ShowGroupPanel="true">
<Columns>
<DxGridDataColumn FieldName="Date" DisplayFormat="D"
AllowGroup="true"
GroupIndex="0" />
@*...*@
</Columns>
</DxGrid>
Edit Data
Edit Modes
The Data Grid and new Grid allow users to edit data in edit and pop-up edit forms. The new Grid also includes extra modes: inline edit row and cell editing.
Each component includes the option that specifies the current edit mode: DxDataGrid`1.EditMode and DxGrid.EditMode. When you migrate to the new Grid, replace the DataGridEditMode enumeration with the GridEditMode enumeration. Values of these enumerations are the same: EditForm
(default value) and PopupEditForm
.
<DxDataGrid Data="@Data"
EditMode="DataGridEditMode.PopupEditForm">
@*...*@
</DxDataGrid>
<DxGrid Data="@Data"
EditMode="GridEditMode.PopupEditForm">
@*...*@
</DxGrid>
Enable Editing
Data Grid
To enable data editing in the Data Grid, do the following:
- Add DxDataGridCommandColumn to display the predefined New, Edit, and Delete command buttons. To hide unnecessary buttons, use the NewButtonVisible, EditButtonVisible, and DeleteButtonVisible properties.
- Handle the following events to post changes to an underlying data source:
- RowInserting / RowInsertingAsync - Fires when a user adds a new row. The event handler accepts a dictionary that lists field names and field values. Once the event handler is processed, the edit form is closed.
- RowUpdating / RowUpdatingAsync - Fires when a user updates a row. The event handler accepts a data item that should be updated and a dictionary that lists field names and new field values. Once the event handler is processed, the edit form is closed.
- RowRemoving / RowRemovingAsync - Fires when a user deletes a row. The event handler accepts a data item that should be deleted.
- Specify the key data field to enable the Data Grid to identify individual data items.
The Data Grid displays the predefined edit form that consists of data editors for each visible column. The editor type depends on the corresponding column’s type. You can disable a column’s EditorVisible property to hide an editor from the edit form. To customize a column’s editor, define the EditTemplate.
<DxDataGrid Data="@Data"
RowRemovingAsync="@OnRowRemoving"
RowUpdatingAsync="@OnRowUpdating"
RowInsertingAsync="@OnRowInserting"
KeyFieldName="Id">
<DxDataGridCommandColumn />
@*...*@
</DxDataGrid>
@code {
// ...
Task OnRowRemoving(Supplier dataItem) {
await NwindDataService.RemoveEmployeeAsync(dataItem);
await UpdateDataAsync();
}
Task OnRowUpdating(Supplier dataItem, IDictionary<string, object> newValues) {
await NwindDataService.UpdateEmployeeAsync(dataItem, newValues);
await UpdateDataAsync();
}
Task OnRowInserting(IDictionary<string, object> newValues) {
await NwindDataService.InsertEmployeeAsync(newValues);
await UpdateDataAsync();
}
}
Grid
To enable data editing in the new Grid, do the following:
- Like for the Data Grid, add DxGridCommandColumn to display the predefined New, Edit, and Delete command buttons. To hide unnecessary buttons, use the NewButtonVisible, EditButtonVisible, and DeleteButtonVisible properties.
Use the EditFormTemplate to define the edit form content. The Grid creates an edit model based on a bound data item. Use the template’s
context
parameter to access this edit model.The default edit form shows only the predefined Save and Cancel buttons. You can disable the EditFormButtonsVisible option to hide these buttons and implement custom buttons.
Handle the following events to post changes to an underlying data source:
EditModelSaving - Fires when a user adds a new row or edits an existing row. Use the event argument’s EditModel property to access the edit model that stores all changes. The DataItem property specifies an actual data item. The IsNew property defines whether the edit model corresponds to a new or existing row.
Once the event handler is processed, the edit form is closed. If you do not save changes to the data source and want to keep the edit form opened, set the event argument’s Cancel property to
true
.- DataItemDeleting - Fires when a user deletes a row. The event argument’s DataItem property specifies the data item that should be removed.
- If your data object has a primary key, assign it to the KeyFieldName or KeyFieldNames property. The Grid uses field values to compare and identify data items. If you do not specify these properties, the Grid uses standard .NET value equality comparison to identify data items.
For detailed information on how to enable data editing and use edit-related options, refer to the following topic: Editing and Validation in Blazor Grid.
<DxGrid Data="@Data"
EditModelSaving="OnEditModelSaving"
DataItemDeleting="OnDataItemDeleting"
KeyFieldName="Id">
<Columns>
<DxGridCommandColumn />
@*...*@
</Columns>
<EditFormTemplate Context="EditFormContext">
@{
var employee = (EditableEmployee)EditFormContext.EditModel;
}
<DxFormLayout CssClass="w-100">
<DxFormLayoutItem Caption="First Name:" ColSpanMd="6">
<DxTextBox @bind-Text="@employee.FirstName" />
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Last Name:" ColSpanMd="6">
<DxTextBox @bind-Text="@employee.LastName" />
</DxFormLayoutItem>
@*...*@
</DxFormLayout>
</EditFormTemplate>
</DxGrid>
@code {
// ...
async Task OnEditModelSaving(GridEditModelSavingEventArgs e) {
if(e.IsNew)
await NwindDataService.InsertEmployeeAsync((EditableEmployee)e.EditModel);
else
await NwindDataService.UpdateEmployeeAsync((EditableEmployee)e.DataItem, (EditableEmployee)e.EditModel);
await UpdateDataAsync();
}
async Task OnDataItemDeleting(GridDataItemDeletingEventArgs e) {
await NwindDataService.RemoveEmployeeAsync((EditableEmployee)e.DataItem);
await UpdateDataAsync();
}
}
Validation
Data Grid
The Data Grid allows you to validate user input based on data annotation attributes. To do this, define the EditFormTemplate to create a custom edit form and use Blazor’s standard EditForm component inside this template as described in this topic.
Grid
The new Grid validates user input automatically based on data annotation attributes. To disable validation, set the ValidationEnabled property to false
.
Other Editing-Related API
The following table describes how to update events and methods related to the edit function when you migrate to the new Grid:
Data Grid (Events) | New Grid (Events) |
---|---|
Data Grid (Methods) | New Grid (Methods) |
Filter Row
Data Grid
To display the filter row in the Data Grid, enable the DxDataGrid.ShowFilterRow option. The filter row displays different in-place editors based on the column types. For more information, refer to the ShowFilterRow property description.
To prevent users from filtering data by individual columns, set their AllowFilter property to false
.
<DxDataGrid Data="@DataSource"
ShowFilterRow="true">
@*...*@
<DxDataGridDateEditColumn Field="Date" DisplayFormat="D" />
<DxGridDataColumn Field="TemperatureC" Caption="@("Temp. (\x2103)")" Width="120px"
AllowFilter="false"/>
@*...*@
</DxDataGrid>
Grid
To display the filter row in the new Grid, enable the property with the same name: DxGrid.ShowFilterRow. The filter row displays a predefined text editor for all data columns. To display a custom editor in the filter row cell, define the FilterRowCellTemplate.
To prevent users from filtering data by individual columns, set their FilterRowEditorVisible property to false
.
<DxGrid Data="@DataSource"
ShowFilterRow="true">
<Columns>
<DxGridDataColumn FieldName="Date" DisplayFormat="D">
<FilterRowCellTemplate>
<DxDateEdit Date="(DateTime?)context.FilterRowValue"
DateChanged="(DateTime? v) => context.FilterRowValue = v"
ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto" />
</FilterRowCellTemplate>
</DxGridDataColumn>
<DxGridDataColumn FieldName="TemperatureC" Caption="@("Temp. (\x2103)")" Width="120px"
FilterRowEditorVisible="false"/>
@*...*@
</Columns>
@*...*@
</DxGrid>
Summary
The new Grid, like the Data Grid, includes the TotalSummary
and GroupSummary
properties used to add summary items. You should replace DxDataGridSummaryItem objects with DxGridSummaryItem objects, and update item properties as shown in the table below.
Data Grid | New Grid |
---|---|
DxDataGridSummaryItem | DxGridSummaryItem |
---|---|
(Accepts SummaryItemType enum values) |
(Accepts GridSummaryItemType enum values) |
ValueDisplayFormat and DisplayText properties | |
- | |
- | |
<DxDataGrid Data="@Data" >
@*...*@
<TotalSummary>
<DxDataGridSummaryItem Field="Date"
SummaryType=SummaryItemType.Min
DisplayFormat="First: {0:D}"/>
<DxDataGridSummaryItem ShowInColumn="TemperatureC"
SummaryType=SummaryItemType.Count/>
</TotalSummary>
</DxDataGrid>
<DxGrid Data="@Data" >
@*...*@
<TotalSummary>
<DxGridSummaryItem FieldName="Date"
SummaryType=GridSummaryItemType.Min
ValueDisplayFormat="D"/>
<DxGridSummaryItem FooterColumnName="TemperatureC"
SummaryType=GridSummaryItemType.Count/>
</TotalSummary>
</DxGrid>
Row Selection
Both the Data Grid and the new Grid support single and multiple row selection. They allow users to select rows by mouse clicks and/or in the selection column.
However, these components have different API members and default behavior as described below.
Data Grid
The Data Grid contains the SelectionMode property that accepts DataGridSelectionMode enumeration values:
SingleSelectedDataRow
(Default Value)MultipleSelectedDataRows
OptimizedMultipleSelection
Users can click rows to select them. To disable row selection, set the SelectionMode property to DataGridSelectionMode.None
.
To access data items that correspond to the selected row(s), use the SingleSelectedDataRow or MultipleSelectedDataRows property depending on selection mode.
To display the selection column, declare a DxDataGridSelectionColumn object between the <DxDataGrid>
and </DxDataGrid>
tags or in the Columns template (see the Declaration section).
<DxDataGrid Data="@Data"
SelectionMode="DataGridSelectionMode.MultipleSelectedDataRows"
@bind-MultipleSelectedDataRows="@SelectedDataItems">
<DxDataGridSelectionColumn />
@*...*@
</DxDataGrid>
@code {
IEnumerable<object> Data { get; set; };
IReadOnlyList<object> SelectedDataItems { get; set; };
// ...
}
Grid
The new Grid also includes the SelectionMode property, but it accepts the following GridSelectionMode enumeration values:
Single
- Use it instead ofSingleSelectedDataRow
.Multiple
(Default Value) - Use it instead ofMultipleSelectedDataRows
andOptimizedMultipleSelection
.
The AllowSelectRowByClick property specifies whether users can select rows by mouse clicks, tap gestures, and keyboard shortcuts. The default property value is false
. To enable row selection, set this property to true
.
To access data items that correspond to the selected row(s), use the SelectedDataItem or SelectedDataItems property depending on selection mode.
To display the selection column, declare a DxGridSelectionColumn object in the Columns template.
<DxGrid Data="@Data"
SelectionMode="GridSelectionMode.Multiple"
AllowSelectRowByClick="true"
@bind-SelectedDataItems="@SelectedDataItems">
<Columns>
<DxGridSelectionColumn />
@*...*@
</Columns>
</DxGrid>
@code {
IEnumerable<object> Data { get; set; }
IReadOnlyList<object> SelectedDataItems { get; set; }
// ...
}
Paging
Both the Data Grid and new Grid can display a pager to enable data navigation. These components also support the page size selector.
The following table maps paging properties that are available in the Data Grid and Grid components:
Data Grid | New Grid |
---|---|
- |
<DxDataGrid Data="@Data"
PageSize="7"
PagerNavigationMode="PagerNavigationMode.InputBox"
PagerPageSizeSelectorVisible="true"
PagerAllowedPageSizes="@(new int[] { 2, 10, 20, 40 })"
PagerAllDataRowsItemVisible="true">
@*...*@
</DxDataGrid>
<DxGrid Data="@Data"
PageSize="7"
PagerNavigationMode="PagerNavigationMode.InputBox"
PageSizeSelectorVisible="true"
PageSizeSelectorItems="@(new int[] { 2, 10, 20, 40 })"
PageSizeSelectorAllRowsItemVisible="true">
@*...*@
</DxGrid>
Vertical Scrolling
Data Grid
The Data Grid includes the VerticalScrollBarMode property that specifies vertical scrollbar visibility: Auto
, Visible
, or Hidden
(Default Value). The VerticalScrollableHeight property defines the height of the scrollable area (in pixels).
Grid
The new Grid displays the vertical scrollbar automatically when Grid content height exceeds the specified height of the component itself. The height of the scrollable area depends on the PageSize property value and the Grid’s height.
Horizontal Scrolling
Data Grid
The Data Grid includes the HorizontalScrollBarMode property that specifies horizontal scrollbar visibility: Auto
, Visible
, or Hidden
(Default Value).
Grid
The new Grid displays the horizontal scrollbar automatically when the total width of all columns exceeds the specified width of the component.
Fixed Columns
Data Grid
Set a column’s FixedStyle property to DataGridFixedStyle.Left
or DataGridFixedStyle.Right
to anchor the column to the Data Grid’s left or right edge.
Grid
Set a column’s FixedPosition property to GridColumnFixedPosition.Left
or GridColumnFixedPosition.Right
to anchor the column to the new Grid’s left or right edge.
Virtual Scrolling
Data Grid
Set the Data Grid’s DataNavigationMode property to VirtualScrolling
to enable virtual scrolling mode.
Grid
Set the new Grid’s VirtualScrollingEnabled property to true
to enable virtual scrolling mode.
Handle a Row Click
Data Grid
The Data Grid allows you to handle clicks on data rows. It includes the RowClick event that fires when a user clicks or double clicks a data row.
Grid
The new Grid allows you to handle clicks on data rows and group rows. It includes the RowClick and RowDoubleClick events that fire when a user clicks or double clicks a grid row.
Templates
Column Display Template
Data Grid
Use a column’s DisplayTemplate property. The Context
parameter returns a processed data item.
<DxDataGrid Data="@Data">
<DxDataGridColumn Field="Date">
<DisplayTemplate>
var inStock = (context as Product).Availability;
@*...*@
</DisplayTemplate>
</DxDataGridColumn>
@*...*@
</DxDataGrid>
Grid
Use the DxGridDataColumn.CellDisplayTemplate property. The Context
parameter returns a GridDataColumnCellDisplayTemplateContext object. To obtain a processed data item, use the parameter’s DataItem property.
<DxGrid Data="@Data" >
<Columns>
<DxGridDataColumn FieldName="Date">
<CellDisplayTemplate>
var inStock = (context.DataItem as Product).Availability;
@*...*@
</CellDisplayTemplate>
</DxGridDataColumn>
</Columns>
@*...*@
</DxGrid>
Other Templates
The Data Grid also allows you to specify a column’s EditTemplate. In the new Grid, you should define the entire edit form template. Refer to the Edit Data section for more information.
The new Grid has no alternative for the DxDataGrid.RowPreviewTemplate supported in the Data Grid.
Row Preview
Data Grid
Specify the RowPreviewTemplate property to show preview sections under each data row across all columns. Use properties of the template’s context
parameter to access the following information:
<DxDataGrid Data="@Data">
<Columns>
@* ... *@
<Columns>
<RowPreviewTemplate Context="ItemInfo">
@{
Employee employee = ItemInfo.DataItem;
<div class="d-flex align-items-start p-1">
<img src="@(StaticAssetUtils.GetImagePath(employee.ImageFileName))" width="76" />
<div class="ps-2 text-wrap">@employee.Notes</div>
</div>
}
</RowPreviewTemplate>
</DxDataGrid>
Grid
Set the DetailRowDisplayMode property to GridDetailRowDisplayMode.Always
and specify the DetailRowTemplate property to show preview sections under each data row across all columns.
Use properties of the template’s context
parameter to access the following information:
<DxGrid Data="GridData"
DetailRowDisplayMode="GridDetailRowDisplayMode.Always">
<Columns>
@* ... *@
</Columns>
<DetailRowTemplate>
@{
var employee = (Employee)context.DataItem;
<text>@employee.Notes</text>
}
</DetailRowTemplate>
</DxGrid>
HTML Decoration
Data Grid
Handle the HtmlRowDecoration and HtmlDataCellDecoration events to color a row or cell, respectively. Use the event arguments (CssClass
, Attributes
, Style
) to customize an element’s appearance.
<DxDataGrid Data="@Data"
HtmlRowDecoration="@OnHtmlRowDecoration"
HtmlDataCellDecoration="@OnHtmlDataCellDecoration">
<Columns>
<DxDataGridColumn Field="@nameof(Invoice.OrderId)" />
@* ... *@
<Columns>
</DxDataGrid>
@code {
void OnHtmlRowDecoration(DataGridHtmlRowDecorationEventArgs<Invoice> eventArgs) {
if(eventArgs.VisibleIndex % 2 == 1)
eventArgs.CssClass = " table-dark";
}
void OnHtmlDataCellDecoration(DataGridHtmlDataCellDecorationEventArgs<Invoice> eventArgs) {
if(eventArgs.DataItem.Quantity > largeOrder) {
eventArgs.CssClass += " font-weight-bold";
}
}
}
Grid
Handle the common CustomizeElement event to customize Grid elements. Use the event’s ElementType argument to identify a target element’s type.
To customize element appearance, use event arguments with the same names as in the Data Grid (CssClass
, Attributes
, Style
).
<DxGrid Data="@Data"
CustomizeElement="Grid_CustomizeElement">
<Columns>
<DxDataGridColumn Field="@nameof(Invoice.OrderId)" />
@* ... *@
<Columns>
</DxGrid>
@code {
void Grid_CustomizeElement(GridCustomizeElementEventArgs e) {
if(e.ElementType == GridElementType.DataRow) {
e.CssClass = " table-dark";
}
if (e.Grid.GetDataItem(e.VisibleIndex).Quantity > largeOrder) {
e.CssClass += " font-weight-bold";
}
}
}
Master-Detail View
Data Grid
Follow the steps below to create hierarchical layouts in the Data Grid:
- Add a master grid to your application.
- Bind the master grid to data and enable its ShowDetailRow property to display detail rows.
- Add the master grid’s columns to the Columns collection.
- Add the DetailRowTemplate template to the grid’s markup to create the detail view. Specify the template’s
context
parameter to access data item properties. - Add the second data grid to the template. Bind the grid to a detail data source that uses the template’s
context
object as a filter criteria. - Specify the KeyFieldName property to enable the grid to identify individual data items.
<DxDataGrid @ref="@grid"
Data="@DataSource"
KeyFieldName="@nameof(Customer.CustomerId)"
ShowDetailRow="true">
<Columns>
<DxDataGridColumn Field="@nameof(Customer.ContactName)" />
@* ... *@
</Columns>
<DetailRowTemplate Context="dataItem">
<DxTabs>
<DxTabPage Text="Invoices">
@* ... *@
</DxTabPage>
<DxTabPage Text="Contact Info">
@* ... *@
</DxTabPage>
</DxTabs>
</DetailRowTemplate>
</DxDataGrid>
@code {
IEnumerable<Customer> DataSource;
DxDataGrid<Customer> grid;
protected override async Task OnInitializedAsync() {
DataSource = await NwindDataService.GetCustomersAsync();
}
}
Grid
Follow the steps below to create hierarchical layouts in the Grid:
- Add a master grid to your application.
- Bind the master grid to data and add columns to its Columns collection.
- Add the DetailRowTemplate to the grid’s markup to create a detail view.
- Optional. We recommend that you allocate the detail grid to a separate component. Separation improves the application structure and prevents excessive component redraw operations.
- Add a second data grid to the template. Bind this grid to a detail data source that uses the template’s context object as a filter criteria.
@inject NwindDataService NwindDataService
<DxGrid @ref="Grid"
Data="MasterGridData">
<Columns>
@* ... *@
</Columns>
<DetailRowTemplate>
<Grid_MasterDetail_NestedGrid_DetailContent Customer="(Customer)context.DataItem" />
</DetailRowTemplate>
</DxGrid>
@code {
IGrid Grid { get; set; }
object MasterGridData { get; set; }
protected override async Task OnInitializedAsync() {
var invoices = await NwindDataService.GetInvoicesAsync();
DetailGridData = invoices
.Where(i => i.CustomerId == Customer.CustomerId)
.ToArray();
}
}
Save and Load Layout
Data Grid
Use the SaveLayout() and LoadLayout(String) methods to save/restore the Data Grid layout on demand. Both methods return and accept the layout object as a JSON string.
You can also handle the following save/restore layout events:
- LayoutChanged - Fires when a user changes a grid’s layout.
- LayoutRestoring - Fires when a grid has been initialized and you can restore its layout (if needed).
<DxDataGrid ...
LayoutRestoring="@OnLayoutRestoring"
LayoutChanged="@OnLayoutChanged">
</DxDataGrid>
@code {
void OnLayoutChanged(IDataGridLayout dataGridLayout) {
var layout = dataGridLayout.SaveLayout();
SaveLayoutToLocalStorage(e.Layout); // Persist the layout in your storage
}
void OnLayoutRestoring(IDataGridLayout dataGridLayout) {
var layout = LoadLayoutFromLocalStorage() ; // Restore layout from your storage
dataGridLayout.LoadLayout(layout);
}
}
Grid
Use the SaveLayout() and LoadLayout(GridPersistentLayout) methods to save/restore the Grid layout on demand. Both methods return and accept the layout object as a GridPersistentLayout instance.
You can also handle the following save/restore events to keep the layout persistence:
- LayoutAutoSaving - Fires when a user changes a grid’s layout.
- LayoutAutoLoading - Fires when a grid has been initialized and you can restore its layout (if needed).
<DxGrid ...
LayoutAutoLoading="Grid_LayoutAutoLoading"
LayoutAutoSaving="Grid_LayoutAutoSaving">
</DxGrid>
@code {
async Task Grid_LayoutAutoLoading(GridPersistentLayoutEventArgs e) {
e.Layout = await LoadLayoutFromLocalStorageAsync(); // Restore layout from your storage
}
async Task Grid_LayoutAutoSaving(GridPersistentLayoutEventArgs e) {
await SaveLayoutToLocalStorageAsync(e.Layout); // Persist the layout in your storage
}
}
Tools
Both Grids allow you to incorporate a toolbar to perform data shaping operations from the UI. Replace the HeaderTemplate with the ToolbarTemplate and use the toolbar without changes:
<DxDataGrid ...>
<HeaderTemplate>
<DxToolbar>
<DxToolbarItem Text="New" IconCssClass="grid-toolbar-new" />
<DxToolbarItem Text="Edit" IconCssClass="grid-toolbar-edit" />
<DxToolbarItem Text="Delete" IconCssClass="grid-toolbar-delete" />
<DxToolbarItem Text="Show Filter Row" IconCssClass="grid-toolbar-filter-row" />
<DxToolbarItem Text="Examples" IconCssClass="grid-toolbar-document" />
</DxToolbar>
</HeaderTemplate>
@* ... *@
</DxDataGrid>
<DxGrid ...>
<ToolbarTemplate>
<DxToolbar>
<DxToolbarItem Text="New" IconCssClass="grid-toolbar-new" />
<DxToolbarItem Text="Edit" IconCssClass="grid-toolbar-edit" />
<DxToolbarItem Text="Delete" IconCssClass="grid-toolbar-delete" />
<DxToolbarItem Text="Show Filter Row" IconCssClass="grid-toolbar-filter-row" />
<DxToolbarItem Text="Examples" IconCssClass="grid-toolbar-document" />
</DxToolbar>
</ToolbarTemplate>
@* ... *@
</DxGrid>