Update DataGrid after Editing Data and Saving via Restful API call

Hey Folks,

I've seen quite a lot of discussion about updating the DataGrid after changes to data so I thought I'd post this to see what people think.

For context all of the Service Class Methods call out to an external API to get and alter data.

Here is the method that get's called when I double-click on the row in the DataGrid:

protected async Task EditRow(DataGridRowMouseEventArgs<AAF2.RadzenStudio.API.Server.Models.AAF2.Contributor> args)
        {
            // Open dialog to edit contributor
            Contributor contributor = await DialogService.OpenAsync<EditContributor>("Edit Contributor", new Dictionary<string, object>() { {"Id", args.Data.Id} });

            if (contributor != null)
            {
                // Locate the existing contributor and update its properties
                var existingContributor = contributors.FirstOrDefault(x => x.Id == contributor.Id);
        
                if (existingContributor != null)
                {
                    existingContributor.Name = contributor.Name;
                    existingContributor.PhoneNumber = contributor.PhoneNumber;
                }
                else
                {
                    // Handle the case where the contributor is not found if necessary
                    // e.g., log a warning or throw an exception
                }
            }
    
            // Refresh the grid and update UI state
            await grid0.Reload();
            StateHasChanged();
        }

Before I updating the underlying collection myself the grid wouldn't reflect the changes made to the data, I read through the documentation and didn't find anything that suggested that grid.Reload() would do this, it looks like it simply refresh the display from the attached data collection.

Is the code above an expected way to keep the grid current with the latest changes to object from an Edit Form ?

Perhaps I should be retrieving this single Contributor back from the API in case calling the Update Method on the Service class (and therefore the API) modified the data in someway which this code wouldn't reflect.

I'd be interested to know what others are doing and the best practice ?

The Reload() method will force the DataGrid to rerender according to the assigned Data - if you use ObservableCollection the DataGrid will be refreshed automatically on any collection change. There is also a EF feature called query tracking (enabled by default for database tables queries) that can handle value changes in the data items and will update the UI:

1 Like

Oh nice - I did'nt realise we would get that behaviour from ObservableCollection, thanks for clearing things up - everything is clear for me now.