# Unsaved-Row Lock in a Blazor Grid

URL: https://flexcoreui.com/demo/grid/unsaved-row-lock  
Section: Data Grid  
Controls: GridControl, GridColumn  
Keywords: row selecting, cancel selection, dirty row, unsaved changes

Stop users losing edits: a Blazor grid's RowSelecting event can cancel the move and hold them on a row until its changes are saved.

## Documentation

### Events

| Name | Type | Description |
|---|---|---|
| RowSelecting | RowSelectEventArgs<TValue> | Before a row is selected by mouse, keyboard or checkbox toggle. Set Cancel to refuse. Not raised by AutoSelectFirstRow, type-ahead moves or the selection methods. |
| RowSelected | RowSelectEventArgs<TValue> | After a row is selected by mouse, keyboard, checkbox toggle, type-ahead search or AutoSelectFirstRow. Not raised during drag-select or by the selection methods. |
| RowDeselecting / RowDeselected | RowSelectEventArgs<TValue> | Declared, but GridControl never raises them. TreeGridControl raises RowDeselected. |

### Args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue? | null | The row. |
| RowIndex | int | 0 | The row's index in the grid's current display order. |
| Cancel | bool | false | Set in RowSelecting to keep the current selection. Ignored by RowSelected. |

### Settings

| Name | Type | Default | Description |
|---|---|---|---|
| Type | SelectionType | SelectionType.Single | Single keeps one row; Ctrl or Shift with a click or an arrow still extends it unless ModifierKeysExtendSelection is off. Multiple: a plain click still collapses to the clicked row; Ctrl toggles a row, Shift selects the visible range from the last selected row. |
| Mode | SelectionMode | SelectionMode.Row | Row or Cell. In Cell mode the selected set is cells, SelectionChanged counts cells, and AutoSelectFirstRow is skipped. |
| ModifierKeysExtendSelection | bool | true | With Single, Ctrl or Shift plus a click or Shift plus an arrow add rows. False keeps exactly one row: a modifier click selects the clicked row alone. Ignored for Multiple and for Cell mode. |

### Cell events

| Name | Type | Description |
|---|---|---|
| OnCellEdit | CellEditArgs<TValue> | Before a batch editor opens on a cell, and before a checkbox toggle or a cell context-menu paste or delete writes its value. Set Cancel to keep the cell as it is. Not raised when an open editor commits. |
| OnCellSave | CellSaveArgs<TValue> | After a cell's value is written: when the batch editor commits on Enter, Tab, blur or a click elsewhere, when a checkbox toggles, and when a context-menu paste or delete, a type-ahead commit or a fill writes a value. Also raised when a touched editor commits the text it started with, so a row can be marked dirty without a change; an untouched editor that commits because focus moved, and an edit abandoned with Escape, raise nothing. There is no cancel: the value is already in the row. |
| CellSaved | CellSavedArgs<TValue> | Declared, but GridControl never raises it. CellSavedArgs has the same three properties as CellSaveArgs. |

### Save args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue | default! | The row the value was written to. |
| ColumnName | string | "" | The column's Field. |
| Value | object? | null | What was written: the committed editor text as a string for a batch edit, the new bool for a checkbox, the pasted or filled object otherwise. |

### Edit args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue | default! | The row. |
| ColumnName | string | "" | The column's Field. |
| Cancel | bool | false | Set to keep the editor closed, or the checkbox or pasted value unwritten. |

### Methods

| Name | Type | Description |
|---|---|---|
| EndEditAsync() | Task | Commits the open batch editor through the same path as Enter, raising OnCellSave; a pending type-ahead is committed and an open row editor saved the same way. Returns without saving when the value fails validation. |
| BeginEditCellAsync(TValue row, string field) | Task | Pages to the row, selects the cell (through RowSelecting and RowSelected) and opens its batch editor as a click would, after OnCellEdit. Does nothing when that is canceled, the column is not editable or edit mode is not Batch; a checkbox cell is selected but not toggled. |

## Examples

### Lock

```razor
@using Fx.ControlKit.Grid

<GridControl TValue="BookingLine"
             DataSource="@_rows"
             ShowRowCountInFooter="true"
             AllowSorting="false"
             AllowSelection="true"
             HighlightSelectedRows="true"
             EnableHover="true"
             Height="340px"
             RowHeight="26"
             MinRowHeight="26"
             EditSettingsRef="@_editSettings"
             SelectionSettingsRef="@_selectionSettings"
             EventsRef="@_events"
             CssClass="fx-grid-compact">
    <GridColumnsBase>
        <GridColumn Field="@nameof(BookingLine.Code)" HeaderText="Line" Width="90px" AllowEditing="false" />
        <GridColumn Field="@nameof(BookingLine.Description)" HeaderText="Description" Width="280px" AllowEditing="true" />
        <GridColumn Field="@nameof(BookingLine.Qty)" HeaderText="Qty" Width="80px" Type="ColumnType.Number" TextAlign="TextAlign.Right" AllowEditing="true" />
        <GridColumn Field="@nameof(BookingLine.Price)" HeaderText="Unit price" Width="100px" Type="ColumnType.Number" TextAlign="TextAlign.Right" AllowEditing="true" Format="$#,##0.00" />
        <GridColumn Field="@nameof(BookingLine.Notes)" HeaderText="Notes" Width="260px" AllowEditing="true" />
    </GridColumnsBase>
</GridControl>
<p class="result">@(_dirtyRow is null ? "No unsaved changes." : $"Unsaved changes on line {_dirtyRow.Code}: {_vetoCount} {(_vetoCount == 1 ? "move" : "moves")} refused.")@(_saveCount > 0 ? $" Saved {_saveCount} {(_saveCount == 1 ? "time" : "times")}." : "")</p>
```

```csharp
public sealed class BookingLine
{
    public string Code { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public decimal Qty { get; set; }
    public decimal Price { get; set; }
    public string Notes { get; set; } = string.Empty;
}

private List<BookingLine> _rows = [];

private bool _dirty;

private BookingLine? _dirtyRow;

private int _vetoCount;

private int _saveCount;

private readonly EditSettings _editSettings = new()
{
    AllowEditing = true,
    Mode = EditMode.Batch
};

private readonly SelectionSettings _selectionSettings = new()
{
    Mode = SelectionMode.Row,
    Type = SelectionType.Single
};

private readonly GridControlEvents<BookingLine> _events = new();

protected override void OnInitialized()
{
    _rows =
    [
        new BookingLine { Code = "10", Description = "Hotel, double room, per night", Qty = 7, Price = 142.00m, Notes = "Late arrival, about 23:30" },
        new BookingLine { Code = "20", Description = "Airport transfer, private car", Qty = 2, Price = 65.00m, Notes = "Meet at arrivals, exit B" },
        new BookingLine { Code = "30", Description = "Sintra day tour, small group", Qty = 2, Price = 89.00m, Notes = "Vegetarian lunch for one" },
        new BookingLine { Code = "40", Description = "Fado dinner show", Qty = 2, Price = 75.00m, Notes = "Table near the stage" },
        new BookingLine { Code = "50", Description = "Lisbon to Porto train, first class", Qty = 2, Price = 48.50m, Notes = "Window seats requested" },
        new BookingLine { Code = "60", Description = "Travel insurance, per traveler", Qty = 2, Price = 39.00m, Notes = "Policy sent with the itinerary" }
    ];

    _events.OnCellSave = EventCallback.Factory.Create<CellSaveArgs<BookingLine>>(this, args =>
    {
        _dirty = true;
        _dirtyRow = args.Data;
    });

    _events.RowSelecting = EventCallback.Factory.Create<RowSelectEventArgs<BookingLine>>(this, args =>
    {
        if (_dirty && _dirtyRow != null && !ReferenceEquals(_dirtyRow, args.Data))
        {
            args.Cancel = true;
            _vetoCount++;
        }
    });
}

private void Save()
{
    _dirty = false;
    _dirtyRow = null;
    _vetoCount = 0;
    _saveCount++;
}
```

