How to Lazy Load JSON Data in .NET MAUI DataGrid
Tags: dotnetmaui, datagrid, development, mobile
Published: 2024-06-19 03:05:08

---
title: How to Lazy Load JSON Data in .NET MAUI DataGrid
published: true
date: 2024-06-10 11:39:13 UTC
tags: dotnetmaui, datagrid, development, mobile
canonical_url: https://www.syncfusion.com/blogs/post/lazy-load-json-data-dotnetmaui-grid
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aatc773gc9vsqqzg65pu.png
---
**TL;DR:** Lazy loading helps us optimize performance by loading data on demand as users scroll rather than fetching all data upfront. Let’s learn to lazy load JSON data in the Syncfusion .NET MAUI DataGrid control. The blog covers setting up the DataGrid, configuring the data source, and handling data requests to ensure smooth, responsive interactions.

As developers, we constantly strive to provide our users a seamless and efficient interaction. One crucial aspect is handling large datasets, especially when presenting them in a tabular format like a DataGrid.

The **lazy loading** or **on-demand loading** technique enhances loading performance. Instead of displaying the entire dataset at once, only a subset is initially loaded. As the user scrolls towards the end of the visible data, more rows are dynamically loaded, providing a smooth and responsive experience.

The [Syncfusion .NET MAUI DataGrid](https://www.syncfusion.com/maui-controls/maui-datagrid ".NET MAUI DataGrid") (SfDataGrid) displays and manipulates data in a tabular view and provides on-demand loading support. 

In this blog, we’ll see how to lazy load **JSON** data using the Syncfusion .NET MAUI DataGrid control!

## Populate JSON data collection from a URI

First, let’s populate a JSON data collection from a URI by following these steps:

**Step 1:** Install the [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/ "Newtonsoft.Json NuGet package") NuGet package in your .NET MAUI project.

**Step 2:** Download the **JSON** data from the URI using the **HttpClient** method and store it in the local file.

Refer to the following code example.

```csharp
public async Task<bool> DownloadJsonAsync()
{
    try
    {
        // Set your REST API URL here.
        Var url = “https://ej2services.syncfusion.com/production/web-services/api/Orders”;

        // Sends requests to retrieve data from the web service for the URI.
        var response = await httpClient.GetAsync(url);
        using (var stream = await response.Content.ReadAsStreamAsync())
        {
            var localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);

            var newpath = Path.Combine(localFolder, "Data.json");

            var fileInfo = new FileInfo(newpath);
            File.WriteAllText(newpath, String.Empty);

            
            using (var fileStream = fileInfo.OpenWrite())
            {
                await stream.CopyToAsync(fileStream);
            }
        }
    }
    catch (OperationCanceledException e)
    {
        System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
        return false;
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
        return false;
    }
    return true;
}
```

**Step 3:** Now, you can get the JSON data as a list of dynamic objects.

Refer to the following code example.

```csharp
private async void GetDataAsync()
{
    isDownloaded = await DataService.DownloadJsonAsync();
    if (isDownloaded)
    {
        var localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var fileText = File.ReadAllText(Path.Combine(localFolder, "Data.json"));

        //Read data from the local path and set it to the collection bound to the DataGrid.
        JSONCollection = JsonConvert.DeserializeObject<IList<dynamic>>(fileText);

        AddProducts(1, 15);
        totalRecords = JSONCollection.Count;
    }
}
```

The [SfDataGrid.LoadMoreCommand](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.DataGrid.SfDataGrid.html#Syncfusion_Maui_DataGrid_SfDataGrid_LoadMoreCommand "SfDataGrid.LoadMoreCommand property of .NET MAUI DataGrid") property gradually uses the JSON data collection to load the items on demand.

Let’s see how to achieve this with code examples!

## Lazy loading JSON data in .NET MAUI DataGrid

To enable the load more feature, set the [AllowLoadMore](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.DataGrid.SfDataGrid.html#Syncfusion_Maui_DataGrid_SfDataGrid_AllowLoadMore "AllowLoadMore property of .NET MAUI DataGrid") property to **true** and use the DataGrid’s [IsBusy](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.DataGrid.SfDataGrid.html#Syncfusion_Maui_DataGrid_SfDataGrid_IsBusy "IsBusy property of .NET MAUI DataGrid") and [LoadMoreCommand](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.DataGrid.SfDataGrid.html#Syncfusion_Maui_DataGrid_SfDataGrid_LoadMoreCommand "LoadMoreCommand property of .NET MAUI DataGrid") properties.

The DataGrid loads a subset of data to its data source at runtime by triggering an **ICommand** bound to the  **LoadMoreCommand** property. This command is executed when tapping on the load more button at the end of the visible data.

Set the  **IsBusy**  property to **true** before loading items to notify DataGrid that more items are about to be loaded. Set the **IsBusy** property to **false** after successfully loading items into the DataGrid.

Refer to the following code example.

```xml
<syncfusion:SfDataGrid x:Name="dataGrid" 
                       AutoGenerateColumnsMode="None"
                       ColumnWidthMode="Fill"
                       ItemsSource="{Binding Records}"
                       AllowLoadMore="True"
                       IsBusy="{Binding IsBusy}"
                       LoadMoreCommand="{Binding LoadMoreRecordsCommand}">
```

Now, define the **LoadMoreRecordsCommand** in the ViewModel.

```csharp
public bool IsBusy
{
    get { return isBusy; }
    set
    {
        isBusy = value;
        OnPropertyChanged("IsBusy");
    }
}

public Command LoadMoreRecordsCommand { get; set; }

public ViewModel()
{
    ........
    ........
    LoadMoreRecordsCommand = new Command(LoadMoreRecords);
}

private async void LoadMoreRecords()
{
    try
    {
        IsBusy = true;
        await Task.Delay(1000);
        var index = Records.Count;
        var count = index + 10 >= totalRecords ? totalRecords - index : 10;
        AddRecords(index, count);
    }
    catch
    {

    }
    finally
    {
        IsBusy = false;
    }
}

private void AddRecords(int index, int count)
{
    for (int i = index; i < index + count; i++)
    {
        Records.Add(JSONCollection[i]);
    }
}
```

Now, you can see the output in the following GIF image.

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/06/Lazy-loading-JSON-data-in-Syncfusion-.NET-MAUI-DataGrid.gif" alt="Lazy loading JSON data in Syncfusion .NET MAUI DataGrid" style="width:100%">

  <figcaption>Lazy loading JSON data in Syncfusion .NET MAUI DataGrid</figcaption>

</figure>

Also, you can show the **Load more** button at the top of the DataGrid control using the [LoadMorePosition](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.DataGrid.SfDataGrid.html#Syncfusion_Maui_DataGrid_SfDataGrid_LoadMorePosition "LoadMorePosition property for .NET MAUI DataGrid") property.

```xml
<syncfusion:SfDataGrid x:Name="dataGrid" 
                     AutoGenerateColumnsMode="None"
                     ColumnWidthMode="FitByHeader"
                     ItemsSource="{Binding Records}"
                     AllowLoadMore="True"
                     IsBusy="{Binding IsBusy}"
                     LoadMorePosition="Top"
                     LoadMoreCommand="{Binding LoadMoreRecordsCommand}">

```

Refer to the following image.

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/06/Placing-load-more-button-at-the-top-of-the-.NET-MAUI-DataGrid.png" alt="Placing load more button at the top of the .NET MAUI DataGrid" style="width:100%">

  <figcaption>Placing load more button at the top of the .NET MAUI DataGrid</figcaption>

</figure>

## References

For more details, refer to the [Lazy load JSON data in .NET MAUI DataGrid GitHub demo](https://github.com/SyncfusionExamples/load-json-data-with-load-more-functionality-in-.net-maui-datagrid "Lazy load JSON data in .NET MAUI DataGrid GitHub demo") and [documentation](https://help.syncfusion.com/maui/datagrid/load-more "Lazy load data in .NET MAUI DataGrid documentation").

## Conclusion

Thanks for reading! In this blog, we’ve seen how to lazy load JSON data in the [.NET MAUI DataGrid](https://www.syncfusion.com/maui-controls/maui-datagrid ".NET MAUI DataGrid") with code examples. Additionally, you can explore and utilize the data binding, sorting, filtering, customization, and other powerful features available in the .NET MAUI DataGrid. We encourage you to try them and share your feedback in the comments below!

Our customers can access the latest version of Essential Studio from the [License and Downloads](https://www.syncfusion.com/account/downloads "Essential Studio License and Downloads page") page. If you’re new to Syncfusion, you can download our [free evaluation](https://www.syncfusion.com/downloads "Get the free evaluation of the Essential Studio products") version to explore all our controls.







## Related blogs

- [Enhancing User Experience: Implementing Typos Tolerance In .NET MAUI Autocomplete](https://www.syncfusion.com/blogs/post/tolerate-typos-maui-autocomplete.aspx "Blog: Enhancing User Experience: Implementing Typos Tolerance In .Net Maui Autocomplete")
- [Sneak Peek At 2024 Volume 1: .NET MAUI](https://www.syncfusion.com/blogs/post/sneak-peek-2024-vol1-dotnet-maui.aspx "Blog: Sneak Peek At 2024 Volume 1: .NET MAUI")
- [Syncfusion’s Response to Xamarin’s End of Life: A Comprehensive Plan](https://www.syncfusion.com/blogs/post/xamarins-end-of-life.aspx "Blog: Syncfusion’s Response to Xamarin’s End of Life: A Comprehensive Plan")
- [Chart Of the Week: Create A .NET MAUI Column Chart to Visualize Which Milk Is the Most Sustainable](https://www.syncfusion.com/blogs/post/maui-columnchart-sustainable-milk.aspx "Blog: Chart Of the Week: Create A .NET MAUI Column Chart to Visualize Which Milk Is the Most Sustainable")