Globalization in Blazor DataGrid

16 May 202524 minutes to read

The Syncfusion Blazor DataGrid provides a feature known as Globalization (global and local), which makes the application more accessible and useful for individuals from different regions and language backgrounds. You have the ability to view data in your preferred language and format, resulting in an enhanced overall experience.

Localization

The Syncfusion Blazor DataGrid supports localization, allowing you to customize the text used in the Grid to suit different languages or cultural preferences. You can change static text on various elements, such as group drop area text and pager information text, to different cultures, such as Arabic, Deutsch, French, and more. For detailed instructions, refer to the Blazor Localization topic to localize Syncfusion Blazor components.

Data Rendering

Locale key words Text Example
Grid_EmptyRecord No records to display Locale empty record
Grid_EmptyDataSourceError DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid  

Columns

Locale key words Text Example
Grid_True true Locale true
Grid_False false Locale false

ColumnChooser

Locale key words Text Example
Grid_Columnchooser Columns Locale columnchooser
Grid_ChooseColumns Choose Column Locale choose columns

Editing

Locale key words Text Example
Grid_Add Add Locale add
Grid_Edit Edit Locale edit
Grid_Cancel Cancel Locale cancel
Grid_Update Update Locale update
Grid_Delete Delete Locale delete
Grid_Save Save Locale save
Grid_EditOperationAlert No records selected for edit operation Locale edit operation alert
Grid_DeleteOperationAlert No records selected for delete operation Locale delete operation alert
Grid_SaveButton Save Locale save button
Grid_OKButton OK Locale ok button
Grid_CancelButton Cancel Locale cancel button
Grid_EditFormTitle Details of Locale edit form title
Grid_AddFormTitle Add New Record Locale add form title
Grid_BatchSaveConfirm Are you sure you want to save changes? Locale batch save confirm
Grid_BatchSaveLostChanges Unsaved changes will be lost. Are you sure you want to continue? Locale batch save lost changes
Grid_ConfirmDelete Are you sure you want to Delete Record? Locale confirm delete
Grid_CancelEdit Are you sure you want to Cancel the changes? Locale cancel edit

Grouping

Locale key words Text Example
Grid_GroupDropArea Drag a column header here to group its column Locale group drop area
Grid_UnGroup Click here to ungroup Locale un group
Grid_GroupDisable Grouping is disabled for this column Locale group disable
Grid_Item item Locale Item
Grid_Items items Locale Items
Grid_UnGroupButton Click here to ungroup  
Grid_GroupDescription Press Ctrl space to group Locale group description

Filtering

Locale key words Text Example
Grid_InvalidFilterMessage Invalid Filter Data  
Grid_FilterbarTitle \s filter bar cell Locale filterbar title
Grid_Matchs No Matches Found Locale matchs
Grid_FilterButton Filter Locale filter button
Grid_ClearButton Clear Locale clear button
Grid_StartsWith Starts With Locale starts with
Grid_EndsWith Ends With Locale ends with
Grid_Contains Contains Locale contains
Grid_Equal Equal Locale equal
Grid_NotEqual Not Equal Locale not equal
Grid_LessThan Less Than Locale less than
Grid_LessThanOrEqual Less Than Or Equal Locale less than or equal
Grid_GreaterThan Greater Than Locale greater than
Grid_GreaterThanOrEqual Greater Than Or Equal Locale greater than or equal
Grid_ChooseDate Choose a Date Locale choose date
Grid_EnterValue Enter the value Locale enter value
Grid_SelectAll Select All Locale select all
Grid_Blanks Blanks Locale blanks
Grid_FilterTrue True Locale filter true
Grid_FilterFalse False Locale filter false
Grid_NoResult No Matches Found Locale no result
Grid_ClearFilter Clear Filter Locale clear filter
Grid_NumberFilter Number Filters Locale number filter
Grid_TextFilter Text Filters Locale text filter
Grid_DateFilter Date Filters Locale date filter
Grid_DateTimeFilter DateTime Filters Locale date time filter
Grid_MatchCase Match Case Locale match case
Grid_Between Between Locale between
Grid_CustomFilter Custom Filter Locale custom filter
Grid_CustomFilterPlaceHolder Enter the value Locale custom filter placeholder
Grid_CustomFilterDatePlaceHolder Choose a date Locale custom filter date placeholder
Grid_AND AND Locale AND
Grid_OR OR Locale OR
Grid_ShowRowsWhere Show rows where: Locale show rows where

Searching

Locale key words Text Example
Grid_Search Search Locale search
Grid_SearchColumns search columns  

Toolbar

Locale key words Text Example
Grid_Print Print Locale print
Grid_Pdfexport PDF Export Locale pdfexport
Grid_Excelexport Excel Export Locale excelexport
Grid_Csvexport CSV Export Locale csvexport

ColumnMenu

Locale key words Text Example
Grid_FilterMenu Filter Locale filter menu
Grid_AutoFitAll Autofit all columns  
Grid_AutoFit Autofit this column  

ContextMenu

Locale key words Text Example
Grid_Copy Copy Locale copy
Grid_Group Group by this column Locale group
Grid_Ungroup Ungroup by this column Locale ungroup
Grid_autoFitAll Auto Fit all columns Locale autofit all
Grid_autoFit Auto Fit this column Locale autofit
Grid_Export Export Locale export
Grid_FirstPage First Page Locale first page
Grid_LastPage Last Page Locale last page
Grid_PreviousPage Previous Page Locale previous page
Grid_NextPage Next Page Locale next page
Grid_SortAscending Sort Ascending Locale sort ascending
Grid_SortDescending Sort Descending Locale sort descending
Grid_EditRecord Edit Record Locale edit record
Grid_DeleteRecord Delete Record Locale delete record

Switch the different localization

The Syncfusion Blazor DataGrid allows you to switch the localization from one culture to another culture. This will be useful when you want to change the localization based on your requirements. For more details, you can refer to the official documentation on dynamically setting the culture.

To switch to a different localization, follow these steps:

Step 1: Create a Blazor web app

You can create a Blazor Web App named LocalizationSample using Visual Studio 2022, either via Microsoft Templates or the Syncfusion® Blazor Extension. Make sure to configure the appropriate interactive render mode and interactivity location.

Step 2: Install Syncfusion Blazor DataGrid and Themes NuGet packages

To add the Syncfusion Blazor DataGrid in the app, open the NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), search and install Syncfusion.Blazor.Grid and Syncfusion.Blazor.Themes.

If your Blazor Web App uses WebAssembly or Auto render modes, install the Syncfusion Blazor NuGet packages in the client project.

Alternatively, use the following Package Manager commands:

Install-Package Syncfusion.Blazor.Grid -Version 29.1.33
Install-Package Syncfusion.Blazor.Themes -Version 29.1.33
Install-Package Syncfusion.Blazor.Buttons -Version 29.1.33

Syncfusion Blazor components are available on nuget.org. Refer to the NuGet packages topic for a complete list of available packages.

Step 3: Register Syncfusion Blazor service

  • Open the ~/_Imports.razor file and import the required namespaces.
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Buttons

Step 4: Add stylesheet and script resources

Include the theme stylesheet and script references in the ~/Components/App.razor file.

<head>
    ....
    <link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
</head>
....
<body>
    ....
    <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
</body>
  • Refer to the Blazor Themes topic for various methods to include themes (e.g., Static Web Assets, CDN, or CRG).
  • Set the rendermode to InteractiveServer or InteractiveAuto in your Blazor Web App configuration.

Step 5: Create and register localization service

Create a SyncfusionLocalizer.cs file and add the following code. For detailed steps on creating and registering a localization service, refer to the Blazor Localization documentation.

using Syncfusion.Blazor;

namespace LocalizationSample.Client
{
    public class SyncfusionLocalizer : ISyncfusionStringLocalizer
    {
        // To get the locale key from mapped resources file
        public string GetText(string key)
        {
            return this.ResourceManager.GetString(key);
        }

        // To access the resource file and get the exact value for locale key

        public System.Resources.ResourceManager ResourceManager
        {
            get
            {
                // Replace the ApplicationNamespace with your application name.
                return LocalizationSample.Client.Resources.SfResources.ResourceManager;
            }
        }
    }
}

Step 6: Configure ~/Program.cs file

  • Set the Culture of the Application: In the client-side ~/Program.cs , use JavaScript Interop to retrieve the user’s culture setting from local storage. If none is found, set the default to en-US.

  • Register Services: Register the SyncfusionLocalizer and Syncfusion Blazor services in both ~/Program.cs files.

using LocalizationSample.Client;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.JSInterop;
using Syncfusion.Blazor;
using System.Globalization;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

// Register the Syncfusion Blazor services.
builder.Services.AddSyncfusionBlazor();

//Register the Syncfusion locale service to localize Syncfusion Blazor components.
builder.Services.AddSingleton(typeof(ISyncfusionStringLocalizer), typeof(SyncfusionLocalizer));
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
var host = builder.Build();

//Setting culture of the application.
var jsInterop = host.Services.GetRequiredService<IJSRuntime>();
var result = await jsInterop.InvokeAsync<string>("cultureInfo.get");
CultureInfo culture;
if (result != null)
{
    culture = new CultureInfo(result);
}
else
{
    culture = new CultureInfo("en-US");
    await jsInterop.InvokeVoidAsync("cultureInfo.set", "en-US");
}
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
await builder.Build().RunAsync();

Step 7: In the project file, add the following code:

<PropertyGroup>
    <BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>
</PropertyGroup>

Step 8: Add javaScript function for culture management

For a Blazor Web App, add the following JavaScript function to the ~/Components/App.razor file (after the Blazor <script> tag and before the closing </body>). This function retrieves and sets the user’s selected culture in the browser’s local storage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="LocalizationSample.styles.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
    <HeadOutlet />
</head>
<body>
    <Routes />
    <script src="_framework/blazor.web.js"></script>
    <script>
        window.cultureInfo = {
            get: () => window.localStorage['BlazorCulture'],
            set: (value) => window.localStorage['BlazorCulture'] = value
        };
    </script>
    <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
</body>
</html>

Step 9: Configure culture switching with Syncfusion Blazor DataGrid

In the Counter.razor file, add the following code to change the culture and display a Grid with a Button to switch between English (en-US) and French (fr-FR):

@page "/counter"
@rendermode InteractiveAuto
@using System.Globalization
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@using LocalizationSample.Client.Data

<div style="padding: 10px 10px">
    <SfButton CssClass="e-outline" @onclick='() => ChangeCulture("en-US")' Content="Change to English (en-US)"></SfButton>
    <SfButton CssClass="e-outline" style="margin-left: 5px;" @onclick='() => ChangeCulture("fr-FR")' Content="Change to French (fr-FR)"></SfButton>
</div>

<SfGrid DataSource="@Orders" AllowFiltering="true" AllowPaging="true" Height="315">
    <GridFilterSettings Type="Syncfusion.Blazor.Grids.FilterType.Menu"></GridFilterSettings>
    <GridColumns>
        <GridColumn Field=@nameof(OrderData.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(OrderData.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
        <GridColumn Field=@nameof(OrderData.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(OrderData.ShipCity) HeaderText="Ship City" Width="130"></GridColumn>
        <GridColumn Field=@nameof(OrderData.ShipCountry) HeaderText="Ship Country" Width="130"></GridColumn>
    </GridColumns>
</SfGrid>

@code {
    public List<OrderData> Orders { get; set; }

    protected override void OnInitialized()
    {
        Orders = OrderData.GetAllRecords();
    }

    private async Task ChangeCulture(string culture)
    {
        await JSRuntime.InvokeVoidAsync("cultureInfo.set", culture);
        NavigationManager.NavigateTo(NavigationManager.Uri, forceLoad: true);
    }
}

Step 11: Create a model class

Create a new folder named Data. Then, add a model class named OrderData.cs in the Data folder to represent the order data.

namespace LocalizationSample.Client.Data
{
    public class OrderData
    {
        public OrderData(int orderID, string customerID, double freight, string shipCity, string shipCountry)
        {
            this.OrderID = orderID;
            this.CustomerID = customerID;
            this.Freight = freight;
            this.ShipCity = shipCity;
            this.ShipCountry = shipCountry;
        }
        public static List<OrderData> GetAllRecords()
        {
            return new List<OrderData>
            {
                new OrderData(10248, "VINET", 32.38, "Reims", "France"),
                new OrderData(10249, "TOMSP", 11.61, "Münster", "Germany"),
                new OrderData(10250, "HANAR", 65.83, "Rio de Janeiro", "Brazil"),
                new OrderData(10251, "VICTE", 41.34, "Lyon", "France"),
                new OrderData(10252, "SUPRD", 51.30, "Charleroi", "Belgium"),
                new OrderData(10253, "HANAR", 58.17, "Rio de Janeiro", "Brazil"),
                new OrderData(10254, "CHOPS", 22.98, "Bern", "Switzerland"),
                new OrderData(10255, "RICSU", 148.33, "Genève", "France"),
                new OrderData(10256, "WELLI", 13.97, "Resende", "Brazil"),
                new OrderData(10257, "HILAA", 81.91, "San Cristóbal", "Mexico"),
                new OrderData(10258, "ERNSH", 140.51, "Graz", "Austria"),
                new OrderData(10259, "CENTC", 3.25, "México D.F.", "Mexico"),
                new OrderData(10260, "OTTIK", 55.09, "Köln", "Germany"),
                new OrderData(10261, "QUEDE", 3.05, "Rio de Janeiro", "Brazil"),
                new OrderData(10262, "RATTC", 48.29, "Albuquerque", "USA")
            };
        }
        public int OrderID { get; set; }
        public string CustomerID { get; set; }
        public double Freight { get; set; }
        public string ShipCity { get; set; }
        public string ShipCountry { get; set; }
    }
}

Step 12: Run the application

When you run the application, the Grid will display data fetched from the API.

Switch the different localization

Right to Left - RTL

The Right to Left (RTL) feature in the Syncfusion Blazor DataGrid allows you to switch the text direction and layout from left-to-right to right-to-left. This feature is especially beneficial for interacting with the Grid in languages that are written and read from right to left, such as Arabic, Farsi, Urdu, and others. Enabling RTL significantly improves the experience and accessibility for such languages.

To enable RTL in the Grid, you can use the EnableRtl property. This property switches the text direction and layout from left-to-right to right-to-left.

To achieve this, follow the steps below:

Step 1: Follow the steps from Step 1 to Step 5 in the following link, then continue with the steps below.

Step 2: Configure ~/Program.cs file

Register the SyncfusionLocalizer and Syncfusion Blazor services in both ~/Program.cs files.

using LocalizationSample.Client;
using Syncfusion.Blazor;

builder.Services.AddSyncfusionBlazor();
builder.Services.AddSingleton(typeof(ISyncfusionStringLocalizer), typeof(SyncfusionLocalizer));

Step 3: Setting the culture in Blazor start option

  • Add the autostart=”false” attribute to the Blazor

  • Add the script block below Blazor’s <script> tag and before the closing </body> tag to start blazor with specific culture.

  • Use the Blazor.start method and set the applicationCulture to the desired culture code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="LocalizationSample.styles.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
    <HeadOutlet />
</head>
<body>
    <Routes />
    <script src="_framework/blazor.web.js" autostart="false"></script>
    <script>
        Blazor.start({
            webAssembly: {
                applicationCulture: 'ar'
            }
        });
    </script>
</body>
</html>

Step 4: Enable or disable RTL mode using toggle Switch

The EJ2 Toggle Switch Button is added to enable or disable the Right-to-Left (RTL) feature for the Arabic (ar-AE) locale. When the switch is toggled, the ValueChange event is triggered, and the EnableRtl property of the Grid is updated accordingly.

@page "/counter"
@rendermode InteractiveAuto

@using LocalizationSample.Client.Models

<div style="display: flex; align-items: center; gap: 10px; padding: 10px;">
    <label style="margin: 0;">Enable or Disable RTL Mode</label>
    <SfSwitch ValueChange="Change" TChecked="bool"></SfSwitch>
</div>


<SfGrid @ref="Grid" DataSource="@Orders" AllowSorting="true" AllowGrouping="true" AllowFiltering="true" ShowColumnMenu="true" ShowColumnChooser="true" AllowPaging="true" Height="315" EnableRtl="@isRTLEnabled" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })">
    <GridFilterSettings Type="Syncfusion.Blazor.Grids.FilterType.Menu"></GridFilterSettings>
    <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" Mode="EditMode.Normal"></GridEditSettings>
    <GridColumns>
        <GridColumn Field=@nameof(OrderData.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(OrderData.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
        <GridColumn Field=@nameof(OrderData.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(OrderData.ShipCity) HeaderText="Ship City" Width="130"></GridColumn>
        <GridColumn Field=@nameof(OrderData.ShipCountry) HeaderText="Ship Country" Width="130"></GridColumn>
    </GridColumns>
</SfGrid>

@code {
    private SfGrid<OrderData> Grid;

    public List<OrderData> Orders { get; set; }
    public bool isRTLEnabled { get; set; } = false;

    protected override void OnInitialized()
    {
        Orders = OrderData.GetAllRecords();
    }

    private void Change(Syncfusion.Blazor.Buttons.ChangeEventArgs<bool> args)
    {
        isRTLEnabled = args.Checked;
        Grid.Refresh();
    }
}

Step 5: Create a model class

Create a new folder named Models. Then, add a model class named OrderData.cs in the Models folder to represent the order data.

namespace LocalizationSample.Client.Models
{
    public class OrderData
    {
        public OrderData(int orderID, string customerID, double freight, string shipCity, string shipCountry)
        {
            this.OrderID = orderID;
            this.CustomerID = customerID;
            this.Freight = freight;
            this.ShipCity = shipCity;
            this.ShipCountry = shipCountry;
        }
        public static List<OrderData> GetAllRecords()
        {
            return new List<OrderData>
            {
                new OrderData(10248, "VINET", 32.38, "Reims", "France"),
                new OrderData(10249, "TOMSP", 11.61, "Münster", "Germany"),
                new OrderData(10250, "HANAR", 65.83, "Rio de Janeiro", "Brazil"),
                new OrderData(10251, "VICTE", 41.34, "Lyon", "France"),
                new OrderData(10252, "SUPRD", 51.30, "Charleroi", "Belgium"),
                new OrderData(10253, "HANAR", 58.17, "Rio de Janeiro", "Brazil"),
                new OrderData(10254, "CHOPS", 22.98, "Bern", "Switzerland"),
                new OrderData(10255, "RICSU", 148.33, "Genève", "France"),
                new OrderData(10256, "WELLI", 13.97, "Resende", "Brazil"),
                new OrderData(10257, "HILAA", 81.91, "San Cristóbal", "Mexico"),
                new OrderData(10258, "ERNSH", 140.51, "Graz", "Austria"),
                new OrderData(10259, "CENTC", 3.25, "México D.F.", "Mexico"),
                new OrderData(10260, "OTTIK", 55.09, "Köln", "Germany"),
                new OrderData(10261, "QUEDE", 3.05, "Rio de Janeiro", "Brazil"),
                new OrderData(10262, "RATTC", 48.29, "Albuquerque", "USA")
            };
        }
        public int OrderID { get; set; }
        public string CustomerID { get; set; }
        public double Freight { get; set; }
        public string ShipCity { get; set; }
        public string ShipCountry { get; set; }
    }
}

Step 6: Run the application

When you run the application, the Grid will display data fetched from the API.

Right to Left - RTL