Blazor Grid CRUD Operations
The Telerik Grid for Blazor supports create, update, and delete operations (CRUD) with different modes and user experience. The component also supports built-in DataAnnotations or custom validation. This page describes:
- How the create, update, and delete operations work in the Grid.
- What are the available edit modes and how to enable them.
- The applicable Grid commands.
- The applicable Grid events.
- How to change the built-in editors for certain data types.
- How to refresh the Grid data after add, edit, and delete operations.
- How the Grid CRUD operations integrate with other component features.
Basics
The Grid CRUD operations rely on the following algorithm:
- Users execute Grid commands (Edit, Save, Delete, and more) with the mouse or keyboard.
- The Grid fires events (
OnCreate,OnDelete,OnUpdateand more), which provide information what the user did or how the component data changed. - The application applies the changes to the Grid data source in the above event handlers.
- The Grid rebinds to display the latest data.
Model Requirements
Adding or editing rows in the Grid sets the following requirements on the Grid model:
- The Grid model class must have a parameterless constructor. Otherwise, use the Grid
OnModelInitevent to provide a data item instance when the Grid needs to create one. Optinally, you can also set some default values. - There must be a non-editable property that serves as a unique identifier.
- All editable properties must be
publicand have setters. These properties must not bereadonly. - All complex properties used in the Grid must be instantiated in the Grid
OnModelInitevent. - Self-referencing or inherited properties must not cause
StackOverflowExceptionorAmbiguousMatchExceptionduring programmatic model instance creation.
Edit Modes
The Grid offers several ways to add and edit rows with a different user experience:
- In-Cell—users modify the Grid content cell by cell.
- Inline—users modify the Grid content row by row.
- Popup—users modify the Grid content row by row in a modal popup form.
To allow users to add or edit values in the Grid:
- Set the
EditModeparameter to a member of theGridEditModeenum. The defaultEditModeparameter value isNoneand the built-inAddandEditcommands don't work. - Define the required command buttons and events for the selected edit mode and operations.
Set up Grid popup edit mode
<TelerikGrid EditMode="@GridEditMode.Popup"
OnUpdate="@OnGridUpdate">
<GridColumns>
<GridCommandColumn>
<GridCommandButton Command="Edit">Edit</GridCommandButton>
</GridCommandColumn>
</GridColumns>
</TelerikGrid>
See the Grid add and edit operations in action in the complete examples for Grid inline, in-cell, and popup editing.
Editing multiple rows at the same time is not supported. You can render editors in all Grid data cells through column
<Template>s as an alternative.
Delete Operations
Delete operations provide the same user experience in all Grid edit modes and require the same configuration:
- Delete command button.
OnDeleteevent.- Optional
ConfirmDeleteGrid parameter. It determines if the component will show a Dialog before firingOnDelete, so that users can abort the operation.
Delete operations can work even if the Grid EditMode parameter value is None.
If the Grid contains Delete command buttons that display and operate in edit mode, these buttons will fire the OnDelete event with a cloned data item instance in the event argument. To find the original data item in the Grid data source, use the item ID or override the Equals() method of the Grid model class.
See the delete operations in action in the complete examples for Grid inline, in-cell, and popup editing. Also check how to customize the Delete Confirmation Dialog.
Commands
The Grid provides the following built-in commands, which enable users to add, delete, and edit rows:
Add—adds a new row and puts it in edit mode. Fires theOnAddevent.Cancel—cancels the row or cell changes and exits edit mode. Fires theOnCancelevent.Delete—deletes a row. Fires theOnDeleteevent.Edit—puts a Grid row or cell in edit mode. Fires theOnEditevent.Save—confirms the row or cell changes and exits edit mode, if the user input is valid. Fires theOnUpdateevent.
Users execute commands in the following ways:
- By clicking on command buttons.
- By clicking on editable cells in in-cell edit mode and then anywhere else on the page.
- By using the Grid keyboard navigation.
Command buttons can only reside in a Grid Command Column or the Grid ToolBar. Each command button in the command column is visible only in display mode or only in edit mode, depending on the button's ShowInEdit boolean parameter value.
You can also trigger add and edit operations programmatically from anywhere on the web page through the Grid State.
Events
The following table describes the Grid events, which are related to adding, deleting, and editing items. Also check the sections about item instances and event arguments below.
| Event | Required | Description | Item Instance | If Cancelled |
|---|---|---|---|---|
OnAdd | No | Fires on Add command button click, before the Grid enters add mode. This event preceeds OnCreate or OnCancel. | New | Grid remains in read mode. |
OnCancel | No | Fires on Cancel command invocation. | New or cloned | Grid remains in add or edit mode. |
OnCreate | To add new items. | Fires on Save command invocation for new items. This event succeeds OnAdd. | New | Grid remains in add mode. |
OnDelete | To delete items. | Fires on Delete command button click. | Original or cloned | Grid won't rebind. Deletion depends on the app itself. |
OnEdit | No | Fires on Edit command invocation, before the Grid actually enters edit mode. This event preceeds OnUpdate or OnCancel. | Original | Grid remains in read mode. |
OnModelInit | Depends on the Grid model type | Fires when the Grid requires a new model instance, which is immediately before OnAdd or immediately after OnEdit. Use this event when the Grid model type is an interface, abstract class, or has no parameterless constructor. | No event arguments | Not cancellable |
OnUpdate | To edit existing items. | Fires on Save command invocation for existing items. This event succeeds OnEdit. | Cloned | Grid remains in edit mode. |
The following considerations apply for the Grid CRUD events:
- Most events provide a
GridCommandEventArgsargument in the handler.OnModelInithas no event argument. - All events, except
OnModelInit, are cancellable and the user action can be prevented. CancellingOnDeletedoes not automatically prevent item deletion from the Grid data source. This depends entirely on the executed application code. - The
OnCreate,OnDelete, andOnUpdateevents are required when using add, delete, and edit operations, respectively. The app must use these events to modify the Grid data source. The Grid does not modify its data directly.
Some events always fire in the same sequence, based on the user actions. In the list below, the value input and validation occur between the second and third event:
OnModelInit,OnAdd, andOnCreatefor add operationsOnEdit,OnModelInit, andOnUpdatefor edit operations
Both user workflows can end with the OnCancel event instead of OnCreate or OnUpdate.
Use
async Taskinstead ofasync voidfor event handlers that execute awaitable operations. Otherwise the Grid may show incorrect data, or the app may throw exceptions related to disposed objects or concurrency.
Item Instances
The Grid does not expose or modify its data items directly in add or edit mode. Instead, the component creates a new item instance or clones an existing one. The user is always changing the values of the separate item instance. The Grid uses Activator.CreateInstance<TItem>() and PropertyInfo.SetValue() to create and populate items for add and edit mode. This approach:
- Allows users to cancel their changes and revert to the original data item values.
- Provides the app with full control over the data source.
- Sets some requirements for the Grid model class and for updating Entity Framework models.
GridCommandEventArgs
All events in the Events table, except OnModelInit, provide a GridCommandEventArgs event argument. It exposes the following properties:
| Property Name | Type | Description |
|---|---|---|
Field | string | The column Field name. Applicable only for in-cell edit mode. |
IsCancelled | bool | Defines if the user action should be prevented. See the Events table for details. |
IsNew | bool | Defines if Item is a newly added row or an existing row. |
Item | object | The data item, which the user is adding, deleting, or editing. Cast it to the Grid model type. |
Value | object | The data item value, which the user is editing. You can cast it to the correct type, based on the Field. Applicable only for in-cell edit mode. |
Column Editors
You can customize the column editors through the column EditorType parameter, or by using an editor template. The EditorType parameter accepts a member of the GridEditorType enum:
| Column Field Type | Valid GridEditorType Enum Members |
|---|---|
bool | CheckBox (default) Switch |
DateTime | DatePicker (default) DateTimePicker TimePicker |
string | TextArea TextBox (default) |
Setting column editor type
<GridColumn Field="@nameof(Race.StartDateTime)"
EditorType="@GridEditorType.DateTimePicker" />
Rebinding After Data Changes
During add, edit, and delete operations, the Grid expects the application to make changes to the data source (database) and then provide the latest data to the component. Reloading the Grid can happen in different ways, depending on the current Grid data binding mechanism.
Data Parameter
In the OnCreate, OnDelete, and OnUpdate event handler, the application must do one of the following:
- Make a read request to the database. Retrieve the latest data and set it as the new value of the Grid
Dataparameter. The Grid will rebind automatically. The following examples demonstrate this approach: - Use the event arguments to update the local item collection in the
Dataparameter manually.
OnRead Event
The Grid automatically fires OnRead immediately after the following events, unless they are cancelled:
OnCancelOnCreateOnDeleteOnUpdate
In this way, the Grid receives the latest data after each operation is complete. If you need to skip the database read request, you can cache the Grid data in the OnRead handler, modify it manually, and reuse it.
Integration with Other Features
Updated rows comply with the current filter, group, search, and sort settings, just like all other rows. As a result, an updated row may render at a different place or disappear. To prevent this temporarily, you can bind the component with OnRead and provide cached data after the edit operation.
When editing a master row in a hierarchy Grid, the respective DetailTemplate will collapse unless you override the Equals() method of the master data item class.
Learn more integration details for the inline and in-cell edit modes.
New Row Position
You can control whether a newly added item appears at the top or bottom of the Grid. Use the NewRowPosition parameter to specify the position. This parameter does not affect Popup edit mode, which always displays a dialog for new items.
This configuration is available in InCell and Inline edit modes. For more details, see the InCell Editing and Inline Editing articles.
When you set
NewRowPositiontoBottom, add the new item at the end of your data collection in theOnCreateevent handler. When set toTop, insert the new item at the beginning of the collection. This ensures the new row appears in the correct position in the view after successfully creating the new record.
Example of adding a new item to the Grid based on the
NewRowPositionvalue
private void OnCreate(GridCommandEventArgs args)
{
if (NewRowPosition == GridNewRowPosition.Bottom)
{
dataCollection.Add(newItem);
}
else // Top
{
dataCollection.Insert(0, newItem);
}
}
Examples
See Grid CRUD operations in action at: