Back to Devexpress

DxGrid.LayoutAutoLoading Event

blazor-devexpress-dot-blazor-dot-dxgrid-ab3f979a.md

latest10.3 KB
Original Source

DxGrid.LayoutAutoLoading Event

Fires when the DxGrid component is initialized and starts to load its layout.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
[Parameter]
public Func<GridPersistentLayoutEventArgs, Task> LayoutAutoLoading { get; set; }

Parameters

TypeDescription
GridPersistentLayoutEventArgs

A GridPersistentLayoutEventArgs object that defines data for this event.

|

Remarks

The Grid allows you to save and restore the component’s layout when necessary. The saved layout object includes the current page, column sort order/direction, column position, filter values, and grouped columns (information about expanded rows in groups is not included).

Handle the LayoutAutoLoading event to restore a grid’s layout when the component is initialized. The component starts loading the layout after the initial component state specified in the markup is applied. As an alternative, call the LoadLayout(GridPersistentLayout) method to restore the layout on demand (for example, on a button click).

Use the Grid event argument and its members to obtain additional information about the Grid. The Layout argument specifies the layout applied to the grid.

Complete any of the following steps to obtain an object that stores the Grid layout:

Note that when <DxGrid> loads the saved layout, the component validates the layout object. If the column collection was modified, the Grid component does not restore the column layout. However, the Grid loads other settings of the component level, such as search text, page size, active page, etc. Handle the LayoutAutoLoading event to update the collection of columns manually.

You can use the following approach to implement different default layouts for mobile and desktop devices:

  • Save layouts to a database instead of browser storage in the LayoutAutoSaving event handler.
  • In the LayoutAutoLoading event handler, use the DxLayoutBreakpoint component to load the layout based on the screen size.

You can save and restore properties not included in the GridPersistentLayout class. Create a structure that stores a GridPersistentLayout instance and use the Grid’s API to save property values. Refer to the following GitHub example for full implementation: https://github.com/DevExpress-Examples/blazor-grid-save-restore-extended-layout.

Example

The following code snippet demonstrates how to ensure the grid’s layout persistence. When the component layout changes, the LayoutAutoSaving event handler saves the updated layout to the browser’s local storage. Once the page is reloaded or restored, the LayoutAutoLoading event handler loads the most recently-saved layout from the local storage and applies it to the grid.

razor
@using System.Text.Json
@inject NwindDataService NwindDataService
@inject IJSRuntime JSRuntime

@if(PreRendered) {
    <DxGrid @ref="Grid" Data="@GridData" AutoExpandAllGroupRows="true"
        ColumnResizeMode="GridColumnResizeMode.NextColumn"
        ShowGroupPanel="true" ShowFilterRow="true"
        PageSizeSelectorVisible="true" PageSizeSelectorAllRowsItemVisible="true"
        LayoutAutoLoading="Grid_LayoutAutoLoading"
        LayoutAutoSaving="Grid_LayoutAutoSaving">
        <Columns>
            <DxGridDataColumn FieldName="Country" GroupIndex="0" />
            <DxGridDataColumn FieldName="City" GroupIndex="1" />
            <DxGridDataColumn FieldName="CompanyName" />
            <DxGridDataColumn FieldName="Address" />
            <DxGridDataColumn FieldName="Phone" />
            <DxGridDataColumn FieldName="ContactName" />
        </Columns>
    </DxGrid>
} else {
    <em>Loading...</em>
}

@code {
    const string LocalStorageKey = "Grid-LayoutPersistence-Data";

    bool PreRendered { get; set; }
    IGrid Grid { get; set; }
    object GridData { get; set; }

    protected override async Task OnInitializedAsync() {
        GridData = await NwindDataService.GetCustomersAsync();
    }

    protected override void OnAfterRender(bool firstRender) {
        if(firstRender) {
            PreRendered = true;
            StateHasChanged();
        }
    }

    async Task Grid_LayoutAutoLoading(GridPersistentLayoutEventArgs e) {
        e.Layout = await LoadLayoutFromLocalStorageAsync();
    }

    async Task Grid_LayoutAutoSaving(GridPersistentLayoutEventArgs e) {
        await SaveLayoutToLocalStorageAsync(e.Layout);
    }

    async Task<GridPersistentLayout> LoadLayoutFromLocalStorageAsync() {
        try {
            var json = await JSRuntime.InvokeAsync<string>("localStorage.getItem", LocalStorageKey);
            return JsonSerializer.Deserialize<GridPersistentLayout>(json);
        } catch {
            // Mute exceptions for the server prerender stage
            return null;
        }
    }

    async Task SaveLayoutToLocalStorageAsync(GridPersistentLayout layout) {
        try {
            var json = JsonSerializer.Serialize(layout);
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", LocalStorageKey, json);
        } catch {
            // Mute exceptions for the server prerender stage
        }
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BlazorDemo.Data.Northwind {
    public class Invoice {
        public string ShipName { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipRegion { get; set; }
        public string ShipPostalCode { get; set; }
        public string ShipCountry { get; set; }
        public string CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Salesperson { get; set; }
        public int OrderId { get; set; }
        public DateTime? OrderDate { get; set; }
        public DateTime? RequiredDate { get; set; }
        public DateTime? ShippedDate { get; set; }
        public string ShipperName { get; set; }
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public decimal UnitPrice { get; set; }
        public short Quantity { get; set; }
        public float Discount { get; set; }
        public decimal? ExtendedPrice { get; set; }
        public decimal? Freight { get; set; }
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BlazorDemo.Data.Northwind {
    public partial class Customer {
        public Customer() {
            Orders = new HashSet<Order>();
        }

        public string CustomerId { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }

        public virtual ICollection<Order> Orders { get; set; }
    }
}
csharp
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlazorDemo.Data.Northwind;
using BlazorDemo.DataProviders;

namespace BlazorDemo.Services {
    public partial class NwindDataService {
        public Task<IEnumerable<Invoice>> GetInvoicesAsync(CancellationToken ct = default) {
            // Return your data here
        }
    }
}
csharp
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlazorDemo.Data.Northwind;
using BlazorDemo.DataProviders;

namespace BlazorDemo.Services {
    public partial class NwindDataService {
        public Task<IEnumerable<Customer>> GetCustomersAsync(CancellationToken ct = default) {
            // Return your data here
        }
    }
}
csharp
// ...
builder.Services.AddScoped<NwindDataService>();

Run Demo: Save and Restore the Layout

See Also

DxGrid Class

DxGrid Members

DevExpress.Blazor Namespace