DxDataGrid<T> Class

A Data Grid component.

Namespace: DevExpress.Blazor

Assembly: DevExpress.Blazor.v20.2.dll

Declaration

public class DxDataGrid<T> :
    DxControlComponent<DxDataGrid<T>, GridJSInteropProxy>,
    IDataSourceSettings<T>,
    IDataGridComponentServiceContainer,
    ISizeModeAccessor,
    IRequireSelfCascading,
    IGridJSInteropProxyServer,
    IJSCallback

Type Parameters

Name Description
T

The data item type.

Remarks

<DxDataGrid> allows you to edit and shape data in a tabular format.

DataGrid Overview

Add Data Grid to a Project

To add the <DxDataGrid> component to an application, follow the steps below:

  1. Create an application. If you use Microsoft project templates, configure the application as described in this topic: Microsoft Templates.
  2. Add the <DxDataGrid>...</DxDataGrid> markup to your application.
  3. Bind the grid to data (see details below).
  4. Configure the component (see the sections below).
NOTE

Detailed instructions: Get Started with Data Grid

Video: Get Started with Data Grid

Bind to Data Synchronously

Use the Data property to bind the grid to a strongly typed collection. Initialize this collection in the OnInitialized lifecycle method or before this method is invoked.

<DxDataGrid Data="@DataSource">
    <DxDataGridDateEditColumn Field=@nameof(WeatherForecast.Date) />
    <DxDataGridColumn Field=@nameof(WeatherForecast.TemperatureC) Caption="Temp. (C)" />
    <DxDataGridSpinEditColumn Field=@nameof(WeatherForecast.TemperatureF) Caption="Temp. (F)" />
</DxDataGrid>

@code {
    IEnumerable<WeatherForecast> DataSource;

    public class WeatherForecast {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }

    protected override void OnInitialized() {
        DataSource = GetForecast();
    }

    public IEnumerable<WeatherForecast> GetForecast() {
        var rng = new Random();
        DateTime startDate = DateTime.Now;
        for (var i = 1; i < 15; i++) {
            yield return new WeatherForecast { Date = startDate.AddDays(i), 
                                               TemperatureC = rng.Next(-15, 20) };
        }
    }
}

The grid can detect IQueryable<T> collections and use benefits of the corresponding LINQ query providers (such as Entity Framework).

Run Demo: Data Grid - Data Binding

Run Demo: Data Grid - Large Datasets

View Example: How to bind a grid to a DataTable object

Bind to Data Asynchronously

Use the DataAsync property instead of the Data property if you bind the grid to a strongly typed collection that is loaded asynchronously (for instance, from an HTTP request). The DataAsync property allows you to prevent the grid's page from excessive re-rendering and draw the grid's skeleton before the data is loaded.

This property specifies an asynchronous function that returns a Task<IEnumerable<T>> object and accepts a CancellationToken object as a parameter. The grid can detect IQueryable<T> collections and use benefits of the corresponding LINQ query providers (such as Entity Framework).

@using System.Threading
@inject WeatherForecastService WeatherForecastService

<DxDataGrid DataAsync="@LoadDataAsync">
    @*...*@
</DxDataGrid>

@code {
    async Task<IEnumerable<WeatherForecast>> LoadDataAsync(CancellationToken token) {
        return await WeatherForecastService.GetForecastAsync(DateTime.Now.Date);
    }
}

The DataAsync function can be called multiple times during the grid's life cycle because Blazor can re-render components. Cache this function if it is time- or resource-consuming.

@using System.Threading
@inject WeatherForecastService WeatherForecastService

<DxDataGrid DataAsync="@LoadDataAsync">
    @*...*@
</DxDataGrid>

@code {
    IEnumerable<WeatherForecast> Cache;
    async Task<IEnumerable<WeatherForecast>> LoadDataAsync(CancellationToken token) {
        if(Cache == null)
            Cache = await WeatherForecastService.GetForecastAsync(DateTime.Now.Date, token);
        return Cache;
    }
}

The DataAsync function receives a cancellation signal in the following cases:

  • The Data Grid is disposed during data retrieve operations. This occurs under the following circumstances:

    • A user switches a tab with the Data Grid component in a tabbed layout.
    • A user navigates to another page.
    • Data Grid is placed inside the if condition and the condition equals false on the last render.
  • A user triggers Data Grid UI update operations too often without waiting until the previous operation is completed (for instance, when users navigate between Data Grid pages before the previous page is loaded).

<DxTabs>
    <DxTabPage Text="Data Grid">
        <DxDataGrid DataAsync="@LoadDataAsync" KeyFieldName="Id">
            @*...*@
        </DxDataGrid>
    </DxTabPage>
    <DxTabPage Text="Cancelled Task Counter">
        Cancelled Task Count: @CancelledTaskCount
    </DxTabPage>
</DxTabs>

@code {
    int CancelledTaskCount = 0;
    async Task<IEnumerable<WeatherForecast>> LoadDataAsync(CancellationToken token) {
        try {
            return await WeatherForecastService.GetForecastAsync(DateTime.Now.Date, token);
        } catch(TaskCanceledException) {
            CancelledTaskCount++;
        }
        return Enumerable.Empty<WeatherForecast>();
    }
}

Run Demo: Data Grid - Asynchronous Data Binding

View Example: How to bind the Data Grid to a data source asynchronously

Bind to Custom Data

If your data is stored on a remote service and is loaded through a Web API, assign the data type to the grid's T parameter and use the CustomData property to implement data load logic. This property specifies an asynchronous function that returns a Task<LoadResult> object and accepts two parameters:

Refer to the CustomData property description for more information and an example.

Run Demo: Data Grid - Custom Data Binding

Columns

To show data in the Data Grid, add columns to the component's markup.

Column Types

The Data Grid ships with the following predefined column types:

NOTE

The columns are added at design time. You cannot change the column collection at runtime.

Use the Field property to bind a column to a data source field, and the Visible property to manage column visibility. For example, set it to false to hide a column. To show, hide, and reorder Data Grid columns at runtime, use the Column Chooser window.

The example below adds all column types listed above. For a sample data source, refer to the following repository on GitHub: WeatherForecastService.cs.

<DxDataGrid DataAsync="@ForecastService.GetForecastAsync">
    <DxDataGridCommandColumn></DxDataGridCommandColumn>
    <DxDataGridDateEditColumn Field="@nameof(WeatherForecast.Date)" DisplayFormat="D" EditorFormat="D">
    </DxDataGridDateEditColumn>
    <DxDataGridColumn Field="@nameof(WeatherForecast.Forecast)"></DxDataGridColumn>
    <DxDataGridSpinEditColumn Field="@nameof(WeatherForecast.TemperatureC)" Caption="@("Temp. (\x2103)")" 
        TextAlignment="DataGridTextAlign.Left" ></DxDataGridSpinEditColumn> 
    <DxDataGridComboBoxColumn Field="@nameof(WeatherForecast.CloudCover)" 
        DataAsync="@ForecastService.GetCloudCoverAsync" TextAlignment="DataGridTextAlign.Left" ></DxDataGridComboBoxColumn>
    <DxDataGridCheckBoxColumn Field="@nameof(WeatherForecast.Precipitation)"></DxDataGridCheckBoxColumn>
</DxDataGrid>

DataGrid Column Types

Run Demo: Data Grid - Column Types

Watch Video : Data Grid - Column Customization

View Example: How to show/hide columns based on the value from external UI elements

View Example: How to use icons instead of default command buttons

Resize Columns

The Data Grid allows users to resize columns at runtime. Users can move the mouse pointer over a column's right border to display a double-sided arrow, and drag the border to change the column's width.

To enable column resize, set the ColumnResizeMode property to one of the following values:

  • NextColumn - The width of the column to the right changes, but the Data Grid's width remains unchanged.

DataGrid Resize Next Column

  • Component - The Data Grid's width changes, but the width of other columns remains the same.

DataGrid Resize Component

<DxDataGrid DataAsync="@CustomersService.Load"
            ...
            ColumnResizeMode="DataGridColumnResizeMode.NextColumn">
    @*...*@
</DxDataGrid>

Run Demo: Data Grid - Resize Columns

Edit Data

The Data Grid allows users to add, edit, and remove data rows. When a user clicks New or Edit, the Data Grid displays the Edit Form.

DataGrid Edit Form

This form consists of data editors for each visible column. The editor type depends on the corresponding column's type.

Column Type

Editor

DxDataGridCheckBoxColumn

DxCheckBox

DxDataGridColumn

DxTextBox

DxDataGridComboBoxColumn

DxComboBox

DxDataGridDateEditColumn

DxDateEdit

DxDataGridSpinEditColumn

DxSpinEdit

Do the following to allow users to edit data:

  1. Add DxDataGridCommandColumn to the Data Grid. This column displays the New, Edit, and Remove command buttons. To hide unnecessary buttons, use the NewButtonVisible, EditButtonVisible, and DeleteButtonVisible properties.
  2. Handle the following events to post changes to an underlying data source:

  3. Handle the InitNewRow event to initialize new data rows.
  4. Specify the key data field to enable the Data Grid to identify individual data items.
@inject SupplierService supplierService

<DxDataGrid Data="@supplierService.GetSuppliersAsync"
            RowRemovingAsync="@OnRowRemoving"
            RowUpdatingAsync="@OnRowUpdating"
            RowInsertingAsync="@OnRowInserting"
            InitNewRow="@OnInitNewRow"
            KeyFieldName="Id">
    @*...*@
</DxDataGrid>

Set the EditMode property to DataGridEditMode.PopupEditForm to display the Edit Form in a pop-up window.

<DxDataGrid Data="@supplierService.GetSuppliersAsync"
            ...
            EditMode="DataGridEditMode.PopupEditForm">
    @*...*@
</DxDataGrid>

DataGrid Popup Edit Form

To customize text displayed in the pop-up Edit Form's header, use the PopupEditFormHeaderText property.

NOTE

If virtual scrolling is enabled, the Data Grid shows the Edit Form in a pop-up window regardless of the EditMode property value.

Use a column's EditorVisible property to show or hide the corresponding editor in the Edit Form. If a column's data type is nullable, you can also use the ClearButtonDisplayMode property to show the Clear button in the editor.

The table below lists other related API members:

Member

Description

RowEditStart / RowEditStartAsync

Fire when the Edit Form is opened to edit a data row.

RowInsertStart / RowInsertStartAsync

Fire when the Edit Form is opened to add a new data row.

RowEditCancel / RowEditCancelAsync

Fire when the Edit Form is closed and discards the changes.

StartRowEdit(Object)

Asynchronously opens the Edit Form for the specified data row or a new row.

CancelRowEdit()

Asynchronously closes the Edit Form and discards the changes.

Run Demo: Data Grid - Edit Data

View Example: How to edit/delete the selected row by clicking on external buttons

View Example: How to edit a row on a separate page

View Example: How to implement the delete confirmation feature

Input Validation and Error Indication

The Data Grid component supports Blazor Form Validation. To validate user input, add the Blazor EditForm component to the EditFormTemplate.

For more information, refer to the following help topic: Validate Input.

<DxDataGrid @ref="@grid"
            Data="@Vacancies">
    <Columns>
        <DxDataGridCommandColumn Width="150px"></DxDataGridCommandColumn>
        ...
    </Columns>
    <EditFormTemplate>
        <EditForm Model="@EditContext" Context="EditFormContext" OnValidSubmit="@HandleValidSubmit">
            <DataAnnotationsValidator />
            <DxFormLayout>
                <DxFormLayoutItem Caption="Vacancy Description:" ColSpanMd="12" Context="FormLayoutContext">
                    <Template>
                        <DxTextBox @bind-Text="@EditContext.Description" />
                    </Template>
                </DxFormLayoutItem>
                ...
            </DxFormLayout>
        </EditForm>
    </EditFormTemplate>
</DxDataGrid>

When a user submits changes, data editors are marked with colored outlines. Green indicates valid values, red - invalid values. If an editor contains an invalid value, all new values are not posted to the data source and the data row is not updated.

Run Demo: Data Grid - Edit Form Template with Validation

Group Data

<DxDataGrid> allows you to group data by multiple columns. To group data by a column, a user should drag its header from the Column Header Panel and drop it onto the Group Panel.

DataGrid Group UI

Users can group grid data when all of the following properties are set to true:

Set a column's GroupIndex property to a zero-based integer value to group grid data in code.

<DxDataGrid Data="@Vacancies" ShowGroupPanel="true">
    <DxDataGridColumn Field="@nameof(Vacancy.Id)" AllowGroup="false"></DxDataGridColumn>
    <DxDataGridColumn Field="@nameof(Vacancy.Description)"></DxDataGridColumn>
    <DxDataGridComboBoxColumn Field="@nameof(Vacancy.Region)" GroupIndex="0"></DxDataGridComboBoxColumn>
    <DxDataGridColumn Field="@nameof(Vacancy.City)" GroupIndex="1"></DxDataGridColumn>
</DxDataGrid>

The grid does not display grouped columns. Set the ShowGroupedColumns property to true to show grouped columns within the grid.

DataGrid ShowGroupedColumns

Drag a column header from the Group Panel back to the Column Header Panel to ungroup grid data by the column. To ungroup grid data in code, set the column's GroupIndex property to -1.

Run Demo: Data Grid - Grouping

Sort Data

Users can click a column header to sort grid data by that column. To change the sort order, they can click the header again. To sort the grid against multiple columns, users should hold the Shift key and click the required columns.

To clear the sort, users can hold the Ctrl key and click the column headers.

To sort data in code, use the following column properties:

  • AllowSort - Specifies whether users can sort data by the column's values.
  • SortOrder - Specifies a column's sort order.
  • SortIndex - Specifies a column's position among sorted columns.

If you do not specify these properties, the Data Grid is sorted by a data source field that is marked with the Key attribute. If the data source does not contain a key field, component data is not sorted.

<DxDataGrid Data="@DataSource">
    <DxDataGridColumn Field="@nameof(ProductFlat.Id)"
                      AllowSort="false">
    </DxDataGridColumn>
    <DxDataGridColumn Field="@nameof(ProductFlat.Category)"
                      SortOrder="DataGridColumnSortOrder.Descending" 
                      SortIndex="0">
    </DxDataGridColumn>
    <DxDataGridColumn Field="@nameof(ProductFlat.Subcategory)"
                      SortOrder="DataGridColumnSortOrder.Ascending"
                      SortIndex="1">
    </DxDataGridColumn>
    <DxDataGridColumn Field="@nameof(ProductFlat.ProductName)"
                      Caption="Product Name">
    </DxDataGridColumn>
</DxDataGrid>

DataGrid Sort

To disable sorting data within the entire grid, set the DxDataGrid.AllowSort property to false.

Run Demo: Data Grid - Sort Data

Filter Data

Enable the ShowFilterRow option to display a row that allows users to filter grid data.

<DxDataGrid Data="@DataSource"
            ShowFilterRow="true">
    @*...*@
</DxDataGrid>

DataGrid Filter Row

The filter row displays different in-place editors depending on the column types.

Column Type

Row Editor

How to Filter

DxDataGridCheckBoxColumn

DxComboBox

A user can select an item from the drop-down list. The filter is applied immediately.

The list contains the following items: True, False, and (optionally) Indeterminate. You can also specify custom text for these items.

DxDataGridColumn

DxTextBox

A user can type text in the editor. The filter is applied after the user presses Enter or the editor loses focus.

DxDataGridComboBoxColumn

DxComboBox

A user can select an item from the drop-down list. The filter is applied immediately.

DxDataGridDateEditColumn

DxDateEdit

A user can select a date from the drop-down calendar and apply the filter immediately.

Alternatively, the user can type a date in the editor. The filter is applied after the user presses Enter or the editor loses focus.

DxDataGridSpinEditColumn

DxSpinEdit

A user can click spin buttons to change a value and apply the filter immediately.

Alternatively, the user can type a value in the editor. The filter is applied after the user presses Enter or the editor loses focus.

To prevent users from filtering data by an individual column, set its AllowFilter property to false.

<DxDataGrid Data="@DataSource"
            ShowFilterRow="true">
    @*...*@
    <DxDataGridColumn Field="@nameof(Order.Product)"
                      AllowFilter="false">
    </DxDataGridColumn>
    @*...*@
</DxDataGrid>

DataGrid Allow Filter

Each editor contains a clear button that resets the filter by the corresponding column. Use DxDataGridCommandColumn to display the common clear button that resets the entire filter.

<DxDataGrid Data="@DataSource"
            ShowFilterRow="true">
    @*...*@
    <DxDataGridCommandColumn NewButtonVisible="false"
                             EditButtonVisible="false"
                             DeleteButtonVisible="false">
    </DxDataGridCommandColumn>
</DxDataGrid>

DataGrid Clear Filter Button

Run Demo: Data Grid - Filter Row

Summary

The Data Grid supports two summary types:

  • Total summaries are calculated across all grid rows and displayed in the grid's footer.
  • Group summaries are calculated across rows within individual groups and displayed in group rows.

Total Summary

Do the following to calculate a total summary:

  1. Add a DxDataGridSummaryItem object to the TotalSummary collection.
  2. Use the item's SummaryType property to specify an aggregate function. The following functions are available: Sum, Min, Max, Avg, and Count.
  3. Set the Field property to the name of a data field whose values take part in calculations. The Min and Max functions require a numeric or date-time data field. The Avg and Sum functions work with numeric fields only.

    The summary value is displayed under the column bound to the specified data field. To show the summary value under another column, specify the ShowInColumn property.

    The Count function does not process any field values. If you select this function, use either the Field or ShowInColumn property to define which column displays the number of rows.

  4. Use the DisplayFormat property to format the summary value. The format pattern can include static text and the predefined placeholders: {0} returns the summary value and {1} returns the parent column’s caption.

    If you do not specify the DisplayFormat property, the following format is applied: {Summary function}: {summary value}. For example, Count: 100 and Sum: 1,000.

  5. You can also specify the following options:
    • Alignment - Specifies the summary item's alignment within a column cell.
    • CssClass - Specifies the name of a CSS class applied to the summary item.
    • Visible - Specifies whether the summary item is visible.
<DxDataGrid Data="@Orders">
    <Columns>
        <DxDataGridDateEditColumn Field="@nameof(Order.OrderDate)" Width="240px" />
        <DxDataGridComboBoxColumn Field="@nameof(Order.CountryId)"
                                  Caption="Ship Country"
                                  Data="@Countries"
                                  ValueFieldName="@nameof(Country.Id)"
                                  TextFieldName="@nameof(Country.CountryName)"
                                  FilteringMode="DataGridFilteringMode.Contains"
                                  Width="250px" />
        <DxDataGridColumn Field="@nameof(Order.Product)" />
        <DxDataGridSpinEditColumn Field="@nameof(Order.UnitPrice)"
                                  DisplayFormat="c"
                                  Width="120px" />
    </Columns>
    <TotalSummary>
        <DxDataGridSummaryItem Field=@nameof(Order.OrderDate)
                               SummaryType=SummaryItemType.Min
                               DisplayFormat="First: {0:D}" />
        <DxDataGridSummaryItem Field=@nameof(Order.UnitPrice)
                               SummaryType=SummaryItemType.Sum
                               DisplayFormat="Sum: {0:c}" />
        <DxDataGridSummaryItem ShowInColumn=@nameof(Order.CountryId)
                               SummaryType=SummaryItemType.Count />
   </TotalSummary>
</DxDataGrid>

Data Grid Total Summary

Run Demo: Data Grid - Total Summary

Group Summary

Do the following to calculate a group summary:

  1. Add a DxDataGridSummaryItem object to the GroupSummary collection.
  2. Use the item's SummaryType property to specify an aggregate function. The following functions are available: Sum, Min, Max, Avg, and Count.
  3. Set the Field property to the name of a data field whose values take part in calculations. The Min and Max functions require a numeric or date-time data field. The Avg and Sum functions work with numeric fields only. The Count function does not process any field values and does not require that you specify the Field property.

  4. Use the DisplayFormat property to format the summary value. The format pattern can include static text and the predefined placeholders: {0} returns the summary value and {1} returns the parent column’s caption.

    If you do not specify the DisplayFormat property, the following format is applied: {Summary function}: {summary value}. For example, Count: 100 and Sum: 1,000.

  5. Use the GroupSummaryPosition property to position the group summary. The following values are available:

<DxDataGrid Data="@SalesData"
            ShowGroupPanel="true">
    <Columns>
        <DxDataGridSpinEditColumn Field=@nameof(SaleInfo.OrderId)
                                  Width="120px" />
        <DxDataGridColumn Field=@nameof(SaleInfo.Region)
                          GroupIndex="0"
                          Width="240px" />
        <DxDataGridColumn Field=@nameof(SaleInfo.Country)
                          GroupIndex="1" />
        <DxDataGridDateEditColumn Field="@nameof(SaleInfo.Date)"
                                  DisplayFormat="D" />
        <DxDataGridColumn Field=@nameof(SaleInfo.City)/>
        <DxDataGridSpinEditColumn Field="@nameof(SaleInfo.Amount)"
                                  DisplayFormat="c"
                                  Width="120px" />
    </Columns>
    <GroupSummary>
        <DxDataGridSummaryItem SummaryType=SummaryItemType.Count
                               GroupSummaryPosition="GroupSummaryPosition.GroupRow" />
        <DxDataGridSummaryItem Field=@nameof(SaleInfo.Amount)
                               SummaryType=SummaryItemType.Sum
                               GroupSummaryPosition="GroupSummaryPosition.GroupFooter"
                               DisplayFormat="Total: {0:c}" />
        <DxDataGridSummaryItem Field=@nameof(SaleInfo.Date)
                               SummaryType=SummaryItemType.Min
                               DisplayFormat="First: {0:D}"
                               GroupSummaryPosition="GroupSummaryPosition.GroupFooter" />
    </GroupSummary>
</DxDataGrid>

Data Grid Group Summary Position

Run Demo: Data Grid - Group Summary

Master-Detail View

The Data Grid component allows you to build master-detail layouts of any complexity. To implement a detailed view, do the following:

  1. Add the master grid to your application.
  2. Bind the master grid to data and enable its ShowDetailRow property to display corresponding detail rows.
  3. Add the master grid's columns to the Columns collection.
  4. Create the detailed view. Add the second data grid to the master grid's DetailRowTemplate and bind this grid to a detail data source that uses the template's context object as a filter criterion.
  5. (Optional) To collapse an expanded detail row when a new detail row is displayed, set the AutoCollapseDetailRow property to true.
  6. Specify the key data field to enable the Data Grid to identify individual data items.
<DxDataGrid @ref="@grid" 
            Data="@ProductsDataSource" 
            AutoCollapseDetailRow="true" 
            ShowDetailRow="true"
            KeyFieldName="Id">
    <Columns>
        <DxDataGridColumn Field="@nameof(Product.Name)" />
        <DxDataGridColumn Field="@nameof(Product.Description)" />
        <DxDataGridSpinEditColumn Field="@nameof(Product.ListPrice)" />
        <DxDataGridSpinEditColumn Field="@nameof(Product.UnitsInInventory)" />
        <DxDataGridSpinEditColumn Field="@nameof(Product.UnitsInManufacturing)" />
    </Columns>
    <DetailRowTemplate>
        <DxTabs>
            <DxTabPage Text="Sales">
                <div class="p-3">
                    @if (SalesDataSource != null) {
                        <DxDataGrid Data="@SalesDataSource.Where(x => x.ProductId == context.Id)" 
                                    SelectionMode="DataGridSelectionMode.None">
                            <DxDataGridDateEditColumn Field="@nameof(Sale.SaleDate)" />
                            <DxDataGridSpinEditColumn Field="@nameof(Sale.Units)" />
                            <DxDataGridSpinEditColumn Field="@nameof(Sale.TotalCost)" />
                            <DxDataGridSpinEditColumn Field="@nameof(Sale.Discount)" />
                        </DxDataGrid>
                    }
                    else {
                        <em>Loading Sales...</em>
                    }
                </div>
            </DxTabPage>
            <DxTabPage Text="Plant Info">
                ...
            </DxTabPage>
        </DxTabs>
    </DetailRowTemplate>
</DxDataGrid>

DataGrid Master Detail

Run Demo Watch Video

Row Selection

Once a user clicks a data row, the row is selected (highlighted). Use the SelectionMode property to specify one of the following selection modes:

  • Single row selection (Default)

    Use the SingleSelectedDataRow property to select a data row in code. Handle the SingleSelectedDataRowChanged event to track selection changes. If data source items are not the same objects on each page load, specify the KeyFieldName property.

  • Multiple row selection

    To select a range of rows, hold down the Shift key and click the first and last rows in the range. To add/remove a row to/from selection, hold down the Ctrl key and click the row.

    Use the MultipleSelectedDataRows property to select data rows in code. Handle the MultipleSelectedDataRowsChanged event to track selection changes. If data source items are not the same objects on each page load, specify the KeyFieldName property.

  • Multiple row selection with optimized performance

    In this mode, the Data Grid stores information about the selection to improve performance. For example, when the number of selected rows exceeds the number of unselected rows, the grid stores information about unselected rows only.

    This mode requires that you set the KeyFieldName property to the name of the data source key field. Handle the OptimizedMultipleSelectionChanged event to track selection changes.

NOTE

To allow users to select multiple rows via checkboxes, add the DxDataGridSelectionColumn to the grid's markup.

The code below demonstrates how to enable Multiple row selection with optimized performance.

<DxDataGrid Data="@DataSource"
            KeyFieldName="Id"
            SelectionMode="DataGridSelectionMode.OptimizedMultipleSelection"
            OptimizedMultipleSelectionChanged="OnSelectionChanged">
        <DxDataGridSelectionColumn />
        <DxDataGridColumn Field="@nameof(ProductFlat.ProductName)" Caption="Product Name"></DxDataGridColumn>
        <DxDataGridColumn Field="@nameof(ProductFlat.Category)"></DxDataGridColumn>
        <DxDataGridColumn Field="@nameof(ProductFlat.Subcategory)"></DxDataGridColumn>
</DxDataGrid>

@code {
    int SelectedCount { get; set; }

    protected async Task OnSelectionChanged(DataGridSelection<ProductFlat> selection) {
        ...
        var selectedKeys = await selection.SelectedKeys;
        SelectedCount = selectedKeys.Count();
    }
}

DataGrid Select a Row

To disable row selection, set the SelectionMode property to None.

Run Demo: Data Grid - Selection

View Example: How to edit/delete the selected row by clicking on external buttons

Handle a Row Click

Each time a user clicks a data row, the grid fires the RowClick event. The examples below demonstrate how you can handle this event.

Double-Click Handler

You can use the RowClick event to handle a double-click on a row. The handler should use the MouseEventArgs.Detail property.

<DxDataGrid @ref="@grid"
            RowClick="@OnRowClick">
    ...
</DxDataGrid>

@code {
    void OnRowClick(DataGridRowClickEventArgs<SampleModel> args) {
        if(args.MouseEventArgs.Detail == 2) {
            // Double-click handler
        }
    }
}

Clear Row Selection

In single selection mode, a user can do any of the following to clear row selection:

  • Click the selected row with the Ctrl key pressed.
  • Click (and select) another row.

You can use the OnRowClick handler to override the default behavior. For example, to cancel row selection, users should not press Ctrl when they click the row:

<DxDataGrid @ref="@grid"
            Data="@Vacancies"
            RowClick="@OnRowClick">
    ...
</DxDataGrid>

@code {
    DxDataGrid<Vacancy> grid;
    IEnumerable<Vacancy> Vacancies;
    ...

    void OnRowClick(DataGridRowClickEventArgs<Vacancy> args) {
        if (grid.IsDataRowSelected(args.DataItem) && !args.MouseEventArgs.CtrlKey) {
            grid.SetDataRowSelected(args.DataItem, false);
            args.Handled = true;
        }
    }
}

Templates

The following templates allow you to customize grid appearance and the Edit Form's layout:

Member

Description

DetailRowTemplate

Specifies a template for detail rows.

DisplayTemplate

Specifies a cell template.

EditTemplate

Specifies a template for editors that correspond to columns within the Edit Form.

EditFormTemplate

Specifies a template for the entire Edit Form.

HeaderTemplate

Specifies a template for the grid header.

RowPreviewTemplate

Specifies a template for preview sections displayed under data rows.

When you define Detail Row, Edit Form, Header or Row Preview templates, use the Columns property to add grid columns.

The code below defines display and edit templates for the Availability column.

<DxDataGrid Data="@DataSource">
    <DxDataGridColumn Field="@nameof(Product.Availability)" Caption="Availability">
        <DisplayTemplate>
            @{
                var id = Guid.NewGuid().ToString();
                var inStock = (context as Product).Availability;
                <input id="@id" type="checkbox" checked="@inStock" disabled readonly />
                if (inStock) {
                    <label class="form-check-label text-success" for="@id"><span>In stock</span></label>
                }
                else {
                    <label class="form-check-label text-danger" for="@id"><span>Sold out</span></label>
                }
            }
        </DisplayTemplate>
        <EditTemplate>
            <DxComboBox Data="@(new List<string>() { "In stock", "Sold out" })"
                        Value="@(((bool)((CellEditContext)context).CellValue) ? "In stock" : "Sold out" )"
                        ValueChanged="@((string newCellValue) => ((CellEditContext)context).OnChanged(newCellValue == "In stock"))">
            </DxComboBox>
        </EditTemplate>
    </DxDataGridColumn>
</DxDataGrid>

DataGrid Display And Edit Templates

Run Demo: Data Grid - Column Templates

Run Demo: Data Grid - Edit Form Template with Validation

Run Demo: Data Grid - Row Preview Template

HTML Decoration

Handle the HtmlRowDecoration and HtmlDataCellDecoration events to highlight rows and cell values.

<DxDataGrid ...
            HtmlRowDecoration="@OnHtmlRowDecoration"
            HtmlDataCellDecoration="@OnHtmlDataCellDecoration">
    <DxDataGridColumn Field="@nameof(Order.Product)">
    </DxDataGridColumn>
    ...
</DxDataGrid>

@code {
    ...
    void OnHtmlRowDecoration(DataGridHtmlRowDecorationEventArgs<Order> eventArgs) {
        if (eventArgs.VisibleIndex % 2 == 1)
            eventArgs.CssClass = " table-dark";
        if (eventArgs.DataItem != null && eventArgs.DataItem.UnitsInOrder > largeOrder)
            eventArgs.CssClass = " table-warning font-weight-bold";
        else
            eventArgs.Attributes.Add("data-low-price", "");
    }

    void OnHtmlDataCellDecoration(DataGridHtmlDataCellDecorationEventArgs<Order> eventArgs) {
        eventArgs.CssClass += " border-0";
        if (eventArgs.Field == nameof(Order.Product)) {
            if (eventArgs.RowVisibleIndex % 2 == 1)
                eventArgs.Style += " background-color: rgb(115, 158, 170);";
            else
                eventArgs.Style += " background-color: rgb(206, 214, 217);";

            if (eventArgs.DataItem.UnitsInOrder > largeOrder)
                eventArgs.CssClass += " font-weight-bold";
        }
    }
}

DataGrid Conditional Highlighting

Run Demo: Data Grid - HTML Decoration

Toolbar

Follow the steps below to add a toolbar to a Data Grid component:

  1. Add HeaderTemplate to the Data Grid’s markup.
  2. Add buttons (DxToolbarItem objects) to the Toolbar component in this template. A button can display an icon, text, or both.

For more information on the Toolbar’s features, refer to the Toolbar component's documentation.

DataGrid Toolbar

Run Demo: Data Grid - Toolbar

Paging

The Data Grid splits a large amount of data rows across multiple pages and displays a pager for data navigation. Use the following properties to set up the pager:

DataGrid Page Size Selector

To hide the pager, set the ShowPager property to false.

Run Demo: Data Grid - Paging

Vertical and Horizontal Scrollbars

You can add a vertical and/or horizontal scrollbar to the Data Grid component.

Virtual Scrolling

Virtual scrolling loads data rows as a user scrolls. Set the DataNavigationMode to VirtualScrolling to enable virtual scrolling.

NOTE

The mode requires that all rows have the same height.

In this mode, the pager is hidden and the Edit Form is shown in a pop-up window.

<DxDataGrid Data="@DataSource" 
    DataNavigationMode="DataGridNavigationMode.VirtualScrolling" >
    ...
</DxDataGrid>

DataGrid NavigationMode

Run Demo: Data Grid - Virtual Scrolling.

Save and Load Layout

Use the SaveLayout() method to save information about the grid's layout to an external storage. The layout information includes the current page, column sort order/direction, column position, filter values, and grouped columns.

NOTE

The saved layout does not include information about expanded rows in groups.

To restore the saved layout, pass the string returned by the SaveLayout method to the LoadLayout(String) method.

The DxDataGrid<T> also provides the following layout-related events:

  • LayoutRestoring - Fires when a grid has been initialized and you can restore its layout (if needed).
  • LayoutChanged - Fires when a user changes a grid's layout.

The code below demonstrates how to save and restore the grid's layout.

<DxDataGrid ...
    LayoutRestoring="@OnLayoutRestoring"
    LayoutChanged="@OnLayoutChanged">
</DxDataGrid>

@code {
     void OnLayoutChanged(IDataGridLayout dataGridLayout) {
        var layout = dataGridLayout.SaveLayout();
        // persist the layout in your storage
    }
    void OnLayoutRestoring(IDataGridLayout dataGridLayout) {
        var layout = … // restore layout from your storage
        dataGridLayout.LoadLayout(layout);
    }
}

View Example: Blazor Data Grid - How to save/load a grid's layout information

Specify the Key Field

The Data Grid should be able to identify individual data items when users edit data, select data rows, or expand detail rows in master-detail layouts.

You can specify the key data field in one of the following ways:

  • Define the Data Grid's KeyFieldName property excplicitly.

    @using System.Threading
    @inject WeatherForecastService WeatherForecastService
    
    <DxDataGrid DataAsync="@LoadDataAsync" KeyFieldName="Id">
        @*...*@
    </DxDataGrid>
    
    @code {
        async Task<IEnumerable<WeatherForecast>> LoadDataAsync(CancellationToken token) {
            return await WeatherForecastService.GetForecastAsync(DateTime.Now.Date);
        }
    }
    
  • Mark the key data field with the Key attribute in a data collection. Note the KeyFieldName property takes priority over this attribute.

    using System;
    using System.ComponentModel.DataAnnotations;
    
    public class WeatherForecast {
        [Key]
        public int Id { get; set; }
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        public string Summary { get; set; }
    }
    

If you do not specify the key field name, the standard Equals method is used to compare data items.

Inheritance

Object
ComponentBase
DevExpress.Blazor.Base.DxDecoratedComponent
DxComponentBase
DxComponentBase<DevExpress.Blazor.Internal.JSInterop.GridJSInteropProxy>
DxControlComponent<DxDataGrid<T>, DevExpress.Blazor.Internal.JSInterop.GridJSInteropProxy>
DxDataGrid<T>
See Also