DxDataGrid<T> Class

A data grid component.

Namespace: DevExpress.Blazor

Assembly: DevExpress.Blazor.dll

Declaration

public class DxDataGrid<T> :
    DxDataGridBase<T>

Type Parameters

Name Description
T

The data item type.

Remarks

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

Blazor-DataGrid-Overview

Add Data Grid to a Project

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

  1. Create and configure the application as described in the Create a New Blazor Application document.
  2. Add the <DxDataGrid>...</DxDataGrid> markup to your application.
  3. Bind the grid to data.
  4. Configure the component (see the sections below).

Bind to Data

Use the Data property to bind the grid to an IEnumerable<T> or IQueryable<T> data source synchronously. If the data source is large or requires access to a remote web service over slow networks, use the DataAsync property instead. It allows you to load data asynchronously and await completion without blocking application code execution.

NOTE

The Data Grid operates in bound mode only. Unbound mode is not supported.

<DxDataGrid Data="@DataSource">
    ...
</DxDataGrid> 

@inject WeatherForecastService ForecastService

@code {
    IEnumerable<WeatherForecast> DataSource;

    protected override async Task OnInitializedAsync()
    {
        DataSource = await ForecastService.GetForecastAsync();
    }
}

To bind the grid to a data source that is not of the IEnumerable<T> or IQueryable<T> type, assign the data source type to the component's T parameter and use the CustomData property to implement data load logic.

Columns

<DxDataGrid> 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 to manage column visibility. For example, set it to false to hide a column.

The following example demonstrates how to add all column types listed above. Refer to our GitHub repository for a sample data source.

<DxDataGrid DataAsync="@ForecastService.GetForecastAsync">
    <DxDataGridCommandColumn></DxDataGridCommandColumn>
    <DxDataGridDateEditColumn Field="@nameof(WeatherForecast.Date)" DisplayFormatString="D" EditFormatString="D">
    </DxDataGridDateEditColumn>
    <DxDataGridColumn Field="@nameof(WeatherForecast.Summary)" Caption="Summary"></DxDataGridColumn>
    <DxDataGridSpinEditColumn Field="@nameof(WeatherForecast.TemperatureC)" Caption="@("Temp. (\x2103)")" 
        TextAlignment="DataGridTextAlign.Left" ></DxDataGridSpinEditColumn> 
    <DxDataGridComboBoxColumn Field="@nameof(WeatherForecast.WeatherType)" Caption="Cloudiness" 
        DataAsync="@ForecastService.GetCloudinessAsync" TextAlignment="DataGridTextAlign.Left" ></DxDataGridComboBoxColumn>
    <DxDataGridCheckBoxColumn Field="@nameof(WeatherForecast.Precipitates)"></DxDataGridCheckBoxColumn>
</DxDataGrid>

Blazor-DataGrid-Column-Types

Edit Data

<DxDataGrid> allows users to edit data. When a user clicks Edit or New, the grid displays the Edit Form. The form consists of data editors for each visible grid column. The editor type depends on the corresponding column's type. When virtual scrolling is enabled, the grid shows the Edit Form in a pop-up window.

Blazor-DataGrid-Edit-Form

Do the following to allow users to edit data:

  1. Add a DxDataGridCommandColumn column to the grid
  2. Implement event handlers to post the changes to the data source:

If a column's data type is nullable, use the ClearButtonDisplayMode property to show the Clear button in the corresponding editor.

<DxDataGrid Data="@DataSource"
            RowInserting="@((newValues) => OnRowInserting(newValues))"
            RowUpdating="@((updatingDataItem, newValues) => OnRowUpdating(updatingDataItem, newValues))"
            RowRemoving="@((dataItem) => OnRowRemoving(dataItem))">
    ...
</DxDataGrid>

The table below lists API members related to data editing:

Member

Description

InitNewRow

Enables you to initialize added data rows.

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 discard the changes.

Input Validation and Error Indication

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

<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.

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.

Blazor_DataGrid_Group_UI

Users can group grid data when all the properties below 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.

Blazor-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.

NOTE

Online Demo: Data Grid - Grouping

Sort Data

Users should click a column header to sort grid data by the corresponding column. To change the sort order, a user should click the header again. The grid can also be sorted against multiple columns. To do this, users should click column headers while Shift is pressed.

To clear sorting by a column, users should click the column header while Ctrl is pressed.

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 sort order.
  • SortIndex - Specifies a column position among sorted columns.
<DxDataGrid Data="@DataSource">
    <DxDataGridColumn Field="@nameof(ProductFlat.Id)"
                      AllowSort="@DefaultBoolean.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>

Blazor-DataGrid-Sort

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

NOTE

Online Demo: Data Grid - Sort Data

Filter Data

The Filter Row allows a user to filter grid data by individual column values.

Blazor-DataGrid-Filter

The Filter Row displays different editors depending on the column types.

  • For the DxDataGridCheckBoxColumn, checkboxes are replaced with a combobox editor. The editor's items have the following captions: True, False, and (optionally) Indeterminate. You can also specify custom texts for the Filter Row.

  • For other column types, the Filter Row uses the same editors as in the Edit Form.

To hide the Filter Row, set the ShowFilterRow property to false.

NOTE

Online Demo: Data Grid - Filter Row

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.
<DxDataGrid @ref="@grid" 
            Data="@ProductsDataSource" 
            AutoCollapseDetailRow="true" 
            ShowDetailRow="true">
    <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" 
                                    ShowFilterRow="false">
                            <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>

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. .

  • 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.

  • 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.

    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();
    }
}

Blazor-DataGrid-Select-a-Row

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

Handle a Row Click

Each time a user clicks a data row, the grid fires the RowClick event.

In single selection mode, a user should do any of the following to unselect a row:

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

The code below overrides the default behavior. In this case, a user should not press Ctrl to click a row and unselect it.

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



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

    ...

    if (grid.IsDataRowSelected(args.DataItem) && !args.MouseEventArgs.CtrlKey) {
       grid.SetDataRowSelected(args.DataItem, false);
       args.Handled = true;
    }
}

Templates

The following templates allow you to customize cell 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.

RowPreviewTemplate

Specifies a template for preview sections displayed under data rows.

When you define Detail Row, Edit Form, 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" })"
                        SelectedItem="@(((bool)((CellEditContext)context).CellValue) ? "In stock" : "Sold out" )"
                        SelectedItemChanged="@(newCellValue => ((CellEditContext)context).OnChanged(newCellValue == "In stock"))">
            </DxComboBox>
        </EditTemplate>
    </DxDataGridColumn>
</DxDataGrid>

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";
        }
    }
}

Blazor-DataGrid-Conditional-Highlighting

NOTE

Online Demo: Data Grid - HTML Decoration

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:

Blazor-DataGrid-Page-Size-Selector

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

NOTE

Online 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.

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>

Blazor-DataGrid-NavigationMode

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, group, and filter values. 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);
    }
}

Inheritance

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