Blazorise DataGrid: Editing
The DataGrid component allows you to dynamically insert, delete, and update records.
Overview
The grid can perform some basic CRUD operations on the supplied Data collection. To enable editing on data-grid, set the Editable attribute to true on the DataGrid, and then set Editable to true on each column you wish to be editable.
By default every time the Item is saved it will be automatically handled by the data-grid itself. That means that all its fields will be populated after the user clicks on Save button. If you want to change that, you can just disable it by setting the UseInternalEditing to false.
Edit Modes
The grid can work in several different editing modes that can provide different user experiences.
EditMode:
Formediting is done in the internal DataGrid formInlineediting is done in the current rowPopupediting is done in the the modal dialogCellany cell value can be edited directly allowing for rapid editing of data.
<Field> <FieldLabel> Edit Mode </FieldLabel> <FieldBody> <Select @bind-Value=""> <SelectItem Value="DataGridEditMode.Form">Form</SelectItem> <SelectItem Value="DataGridEditMode.Inline">Inline</SelectItem> <SelectItem Value="DataGridEditMode.Popup">Popup</SelectItem> <SelectItem Value="DataGridEditMode.Cell">Cell ("Rapid Editing")</SelectItem> </Select> </FieldBody> </Field> <DataGrid TItem="Employee" Data="" @bind-SelectedRow="" Editable Responsive ShowPager CommandMode="DataGridCommandMode.ButtonRow" EditMode="editMode"> <DataGridColumns> <DataGridCommandColumn NewCommandAllowed="false" EditCommandAllowed="false" DeleteCommandAllowed="false" CancelCommandAllowed> <SaveCommandTemplate> <Button ElementId="btnSave" Type="ButtonType.Submit" PreventDefaultOnSubmit Color="Color.Primary" Clicked="@context.Clicked">@context.LocalizationString</Button> </SaveCommandTemplate> <CancelCommandTemplate> <Button ElementId="btnCancel" Color="Color.Secondary" Clicked="@context.Clicked">@context.LocalizationString</Button> </CancelCommandTemplate> </DataGridCommandColumn> <DataGridColumn Field="@nameof( Employee.Id )" Caption="#" Sortable="false" /> <DataGridColumn Field="@nameof( Employee.FirstName )" Caption="First Name" Editable /> <DataGridColumn Field="@nameof( Employee.LastName )" Caption="Last Name" Editable /> <DataGridColumn Field="@nameof( Employee.Email )" Caption="Email" Editable /> <DataGridNumericColumn Field="@nameof( Employee.Salary )" Caption="Salary" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo( "fr-FR" )" Editable /> </DataGridColumns> <ButtonRowTemplate> <Button Color="Color.Success" Clicked="context.NewCommand.Clicked">New</Button> <Button Color="Color.Primary" Disabled="( selectedEmployee is null )" Clicked="context.EditCommand.Clicked">Edit</Button> <Button Color="Color.Danger" Disabled="( selectedEmployee is null )" Clicked="context.DeleteCommand.Clicked">Delete</Button> <Button Color="Color.Link" Clicked="context.ClearFilterCommand.Clicked">Clear Filter</Button> </ButtonRowTemplate> </DataGrid>
@code { private readonly EmployeeData EmployeeData = new(); private List<Employee> employeeList; private Employee selectedEmployee; private DataGridEditMode editMode = DataGridEditMode.Form; protected override async Task OnInitializedAsync() { employeeList = await EmployeeData.GetDataAsync(); await base.OnInitializedAsync(); } }
Rapid Editing
For a rapid editing experience, similar to how an excel document works, we recommend enabling the following options:
NavigationMode- Defines the DataGrid navigation mode, allowing to control the navigation via keyboard.DataGridEditMode.Cell- This allows to edit the cells directly by pressing the Enter key or any text key.DataGridEditModeOptions.CellEditSelectTextOnEdit- When a cell enters edit mode the text will be selected allowing the user to quickly copy or replace it.
It is also of note that you can use the DataGridEditModeOptions to further configure how the feature will work.
For instance, in the following example we're using the recommended options to enable rapid editing, and we're using the CellEditOnSingleClick and CellEditOnDoubleClick edit options to disable the cell editing on single click and double click.
<Field> <FieldBody> <Switch @bind-Value="" Size="Size.Medium">Show Command Column</Switch> </FieldBody> </Field> <DataGrid TItem="Employee" Data="" @bind-SelectedRow="" Editable Responsive ShowPager CommandMode="DataGridCommandMode.ButtonRow" EditMode="DataGridEditMode.Cell" NavigationMode="DataGridNavigationMode.Cell" EditModeOptions="new() { CellEditOnSingleClick = false, CellEditOnDoubleClick = false, CellEditSelectTextOnEdit = true }"> <DataGridColumns> @if ( showCommandColumn ) { <DataGridCommandColumn NewCommandAllowed="false" EditCommandAllowed="false" DeleteCommandAllowed="false" CancelCommandAllowed> <SaveCommandTemplate> <Button ElementId="btnSave" Type="ButtonType.Submit" PreventDefaultOnSubmit Color="Color.Primary" Clicked="@context.Clicked">@context.LocalizationString</Button> </SaveCommandTemplate> <CancelCommandTemplate> <Button ElementId="btnCancel" Color="Color.Secondary" Clicked="@context.Clicked">@context.LocalizationString</Button> </CancelCommandTemplate> </DataGridCommandColumn> } <DataGridColumn Field="@nameof( Employee.Id )" Caption="#" Sortable="false" /> <DataGridColumn Field="@nameof( Employee.FirstName )" Caption="First Name" Editable /> <DataGridColumn Field="@nameof( Employee.LastName )" Caption="Last Name" Editable /> <DataGridColumn Field="@nameof( Employee.Email )" Caption="Email" Editable /> <DataGridNumericColumn Field="@nameof( Employee.Salary )" Caption="Salary" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo( "fr-FR" )" Editable /> </DataGridColumns> </DataGrid>
@code { private readonly EmployeeData EmployeeData = new(); private List<Employee> employeeList; private Employee selectedEmployee; private bool showCommandColumn; protected override async Task OnInitializedAsync() { employeeList = await EmployeeData.GetDataAsync(); await base.OnInitializedAsync(); } }
Batch Edit
The grid can be set to batch edit mode by setting BatchEdit to true. This allows the user to edit multiple rows and then save all the changes at once.
@using System @using System.Collections.Generic @using System.ComponentModel.DataAnnotations @using System.Linq @using System.Threading.Tasks <Field> <FieldLabel> Edit Mode </FieldLabel> <FieldBody> <Select @bind-Value=""> <SelectItem Value="DataGridEditMode.Form">Form</SelectItem> <SelectItem Value="DataGridEditMode.Inline">Inline</SelectItem> <SelectItem Value="DataGridEditMode.Popup">Popup</SelectItem> <SelectItem Value="DataGridEditMode.Cell">Cell ("Rapid Editing")</SelectItem> </Select> </FieldBody> </Field> <DataGrid @ref=dataGridRef TItem="Employee" Data="inMemoryData" Responsive ShowPager ShowPageSizes @bind-SelectedRow="" Editable EditMode="" BatchEdit BatchChange="OnBatchChange" BatchSaving="OnBatchSaving" BatchSaved="OnBatchSaved" UseValidation ValidationsSummaryLabel="The following validation errors have occurred..." CommandMode="DataGridCommandMode.ButtonRow" ShowValidationsSummary> <DataGridColumns> <DataGridCommandColumn SaveBatchCommandAllowed=false CancelBatchCommandAllowed=false /> <DataGridColumn TextAlignment="TextAlignment.Center" TItem="Employee" Field="@nameof( Employee.Id )" Caption="#" Width="Width.Px( 60 )" /> <DataGridColumn TItem="Employee" Field="@nameof( Employee.FirstName )" Caption="First Name" Editable /> <DataGridColumn TItem="Employee" Field="@nameof( Employee.LastName )" Caption="Last Name" Editable /> <DataGridColumn TItem="Employee" Field="@nameof( Employee.Email )" Caption="Email" Editable /> <DataGridColumn TItem="Employee" Field="@nameof( Employee.Salary )" Caption="Salary" Editable Width="Width.Px( 140 )" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo( "fr-FR" )" TextAlignment="TextAlignment.End" /> </DataGridColumns> <ButtonRowTemplate> <Button Color="Color.Success" Clicked="context.NewCommand.Clicked">New</Button> <Button Color="Color.Primary" Disabled="( selectedEmployee is null )" Clicked="context.EditCommand.Clicked">Edit</Button> <Button Color="Color.Danger" Disabled="( selectedEmployee is null )" Clicked="context.DeleteCommand.Clicked">Delete</Button> <Button Color="Color.Link" Clicked="context.ClearFilterCommand.Clicked">Clear Filter</Button> <Button Color="Color.Success" Disabled="( batchQuantity == 0 )" Clicked="@(context.SaveBatchCommand.Clicked)">@context.SaveBatchCommand.LocalizationString</Button> <Button Color="Color.Default" Clicked="@(context.CancelBatchCommand.Clicked)">@context.CancelBatchCommand.LocalizationString</Button> </ButtonRowTemplate> </DataGrid>
@code { private readonly EmployeeData EmployeeData = new(); private int batchQuantity = 0; private DataGrid<Employee> dataGridRef; private List<Employee> inMemoryData; private Employee selectedEmployee; private DataGridEditMode editMode = DataGridEditMode.Form; protected override async Task OnInitializedAsync() { inMemoryData = ( await EmployeeData.GetDataAsync().ConfigureAwait( false ) ).Take( 25 ).ToList(); await base.OnInitializedAsync(); } private Task OnBatchChange( DataGridBatchChangeEventArgs<Employee> args ) { Console.WriteLine( "Batch Change" ); batchQuantity = dataGridRef.BatchChanges.Count; return Task.CompletedTask; } private Task OnBatchSaving( DataGridBatchSavingEventArgs<Employee> args ) { Console.WriteLine( "Batch Saving" ); return Task.CompletedTask; } private Task OnBatchSaved( DataGridBatchSavedEventArgs<Employee> args ) { Console.WriteLine( "Batch Saved" ); batchQuantity = 0; return Task.CompletedTask; } public class Gender { public string Code { get; set; } public string Description { get; set; } } public class EmployeeData { private static readonly string[] FirstNames = ["Samuel", "Irvin", "Cora", "Jessie", "Maryann", "Kara"]; private static readonly string[] LastNames = ["Collier", "Ziemann", "Conn", "Wilkinson", "Hilpert", "Brekke"]; private static readonly string[] Cities = ["London", "Paris", "New York", "Berlin", "Lisbon", "Zagreb"]; public static IEnumerable<Gender> Genders = [ new() { Code = null, Description = string.Empty }, new() { Code = "M", Description = "Male" }, new() { Code = "F", Description = "Female" }, new() { Code = "D", Description = "Diverse" } ]; public Task<List<Employee>> GetDataAsync() => Task.FromResult( Enumerable.Range( 1, 500 ) .Select( index => { string firstName = FirstNames[( index - 1 ) % FirstNames.Length]; string lastName = LastNames[( index - 1 ) % LastNames.Length]; return new Employee { Id = index, FirstName = firstName, LastName = lastName, Email = $"{firstName}.{lastName}{index}@example.com", City = Cities[( index - 1 ) % Cities.Length], Zip = $"{10000 + index}", DateOfBirth = new DateTime( 1950 + index % 50, 1 + index % 12, 1 + index % 28 ), Childrens = index % 6, Gender = index % 3 == 0 ? "D" : index % 2 == 0 ? "F" : "M", Salary = 50000m + index * 137m % 50000m, IsActive = index % 2 == 0, Salaries = Enumerable.Range( 1, index % 4 ) .Select( month => new Salary { Date = new DateTime( 2025, month, 1 ), Total = 1000m + index * month * 11m } ) .ToList() }; } ) .ToList() ); } public class Employee { public Employee() { } public Employee( Employee other ) { Id = other.Id; Childrens = other.Childrens; DateOfBirth = other.DateOfBirth; City = other.City; Email = other.Email; FirstName = other.FirstName; LastName = other.LastName; Gender = other.Gender; IsActive = other.IsActive; Salaries = other.Salaries; Salary = other.Salary; Tax = other.Tax; Zip = other.Zip; } [Display( Name = "Id" )] public int Id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] [EmailAddress] [Display( Name = "Email" )] public string Email { get; set; } [Display( Name = "City" )] public string City { get; set; } [Display( Name = "Zip" )] public string Zip { get; set; } [Display( Name = "DOB" )] public DateTime? DateOfBirth { get; set; } [Display( Name = "Childrens" )] public int? Childrens { get; set; } [Display( Name = "Gender" )] public string Gender { get; set; } [Display( Name = "Salary" )] public decimal Salary { get; set; } [Display( Name = "Tax" )] public decimal Tax { get { if ( tax == 0 && Salary > 0 ) { tax = Salary * TaxPercentage; } return tax; } set { tax = value; } } [Display( Name = "Active" )] public bool IsActive { get; set; } public List<Salary> Salaries { get; set; } = new(); public decimal ChildrensPerSalary => Salary == 0m ? 0m : ( Childrens is null || Childrens == 0 ? 1 : Childrens.Value ) / Salary; public decimal TaxPercentage = 0.25m; private decimal tax; } public class Salary { public DateTime Date { get; set; } public decimal Total { get; set; } } }
NewItemDefaultSetter
NewItemDefaultSetter function is used to set default values when new item is created and before the edit form is shown. It will only be evaluate, if DataGrid is editable.
<DataGrid TItem="Employee" Data="" @bind-SelectedRow="" NewItemDefaultSetter="" Editable Responsive ShowPager> <DataGridCommandColumn /> <DataGridColumn Field="@nameof( Employee.Id )" Caption="#" Sortable="false" /> <DataGridColumn Field="@nameof( Employee.FirstName )" Caption="First Name" Editable /> <DataGridColumn Field="@nameof( Employee.LastName )" Caption="Last Name" Editable /> <DataGridColumn Field="@nameof( Employee.Email )" Caption="Email" Editable /> <DataGridColumn Field="@nameof( Employee.Salary )" Caption="Salary" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo( "fr-FR" )" Editable> <EditTemplate> <NumericInput TValue="decimal" Value="@((decimal)context.CellValue)" ValueChanged="@(v => context.CellValue = v)" /> </EditTemplate> </DataGridColumn> </DataGrid>
@code { private readonly EmployeeData EmployeeData = new(); private List<Employee> employeeList; private Employee selectedEmployee; protected override async Task OnInitializedAsync() { employeeList = await EmployeeData.GetDataAsync(); await base.OnInitializedAsync(); } void OnEmployeeNewItemDefaultSetter( Employee employee ) { employee.Salary = 100.0M; employee.IsActive = true; } }
Cascading values
In some case you want to update a different cell in a DataGrid when you update a value. This can be achieved with an UpdateCell method. You have two ways of updating a cell:
- by calling
UpdateCellon the context inside ofEditTemplate, or - by calling
UpdateCellEditValueon theDataGridinstance
In the following example we're simply calling context.UpdateCell with a field-name to change and a new value that we want it to assign:
<DataGrid TItem="Employee" Data="" Editable EditMode="DataGridEditMode.Inline" Responsive ShowPager> <DataGridCommandColumn /> <DataGridColumn Field="@nameof( Employee.Salary )" Caption="Salary" Editable DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")"> <EditTemplate> <NumericInput TValue="decimal" Value="@((decimal)context.CellValue)" ValueChanged="@( v => { context.CellValue = v; context.UpdateCell( nameof( Employee.Tax ), v * context.Item.TaxPercentage ); })" /> </EditTemplate> </DataGridColumn> <DataGridColumn Field="@nameof( Employee.Tax )" Caption="Tax" Editable DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")"> <EditTemplate> <NumericInput TValue="decimal" Value="@((decimal)context.CellValue)" Disabled /> </EditTemplate> </DataGridColumn> </DataGrid>
@code { private readonly EmployeeData EmployeeData = new(); private List<Employee> employeeList; protected override async Task OnInitializedAsync() { employeeList = await EmployeeData.GetDataAsync(); await base.OnInitializedAsync(); } }
API
See the documentation below for a complete reference to all of the props and classes available to the components mentioned here.