How to Lazy Load JSON Data in .NET MAUI DataGrid
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (180).NET Core  (28).NET MAUI  (226)Angular  (113)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (41)Black Friday Deal  (1)Blazor  (236)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (199)File Formats  (72)Flutter  (136)JavaScript  (226)Microsoft  (121)PDF  (83)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (963)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (163)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (10)Business intelligence  (55)Button  (4)C#  (164)Chart  (147)Chart of the week  (58)Cloud  (15)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (73)Development  (679)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (21)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (522)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (45)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (113)UI  (405)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (627)What's new  (340)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Efficient Data Handling in .NET MAUI DataGrid: Implementing Lazy Loading with JSON Data

How to Lazy Load JSON Data in .NET MAUI DataGrid

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

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.

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 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 property to true and use the DataGrid’s IsBusy and LoadMoreCommand 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.

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

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.

Lazy loading JSON data in Syncfusion .NET MAUI DataGrid
Lazy loading JSON data in Syncfusion .NET MAUI DataGrid

Also, you can show the Load more button at the top of the DataGrid control using the LoadMorePosition property.

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

Placing load more button at the top of the .NET MAUI DataGrid
Placing load more button at the top of the .NET MAUI DataGrid

References

For more details, refer to the Lazy load JSON data in .NET MAUI DataGrid GitHub demo and documentation.

Supercharge your cross-platform apps with Syncfusion's robust .NET MAUI controls.

Conclusion

Thanks for reading! In this blog, we’ve seen how to lazy load JSON data in the .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 page. If you’re new to Syncfusion, you can download our free evaluation version to explore all our controls.

If you have any questions or need assistance, contact us through our support forumssupport portal, or feedback portal. We’re here and excited to assist you!

Test Flight
App Center Badge
Google Play Store Badge
Microsoft Badge
Github Store Badge

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed