Skip to content

Latest commit

 

History

History
125 lines (91 loc) · 3.7 KB

grid-default-value-for-new-row.md

File metadata and controls

125 lines (91 loc) · 3.7 KB
title description type page_title slug position tags ticketid res_type
Set Default Values for New Grid Rows
Learn how to set default values when the user adds new data items to a Telerik Grid or Telerik TreeList for Blazor.
how-to
How to Set Default Values for New Grid Rows
grid-kb-default-value-for-new-row
blazor, grid, treelist, crud
1433032
kb

Environment

Product Grid for Blazor,
TreeList for Blazor

Description

This KB article answers the following questions:

  • How to apply predefined default values to data item properties when adding new rows to the Grid?
  • How to set default values that are used when I create a new row? For example, I want to default a date to January 1 of next year instead of null or Jan 1, 0001.

Solution

There are several ways to set default values in a new Grid or TreeList row:

Model Class

Setting default values in the model class is independent of the Grid component.

caption Set default values inline

public class Order
{
    public int Quantity { get; set; } = 10;

    public DateTime Received { get; set; } = DateTime.Now;
}

caption Set default values in the constructor method

public class Order
{
    public int Quantity { get; set; }

    public DateTime Received { get; set; }

    public Order()
    {
        Quantity = 10;
        Received = DateTime.Now;
    }
}

OnAdd Event

The Grid OnAdd event fires when the user clicks on the Add command button and before the Grid renders the new row. Set the default values to the Item property of the GridCommandEventArgs event argument.

caption Set default values in the Grid OnAdd event

private void OnGridAdd(GridCommandEventArgs args)
{
    var newItem = (Order)args.Item;
    newItem.Quantity = 10;
    newItem.Received = DateTime.Now;
}

See complete runnable examples for inline, popup, and in-cell edit mode.

OnModelInit Event

The Grid OnModelInit event fires when the Grid needs a new model instance for add or edit mode. Set the default values to the item object that the event handler returns.

caption Set default values in the OnAdd event

private Order OnGridModelInit()
{
    return new Order()
    {
        Quantity = 10,
        Received = DateTime.Now
    };
}

See complete runnable examples for inline, popup, and in-cell edit mode.

Grid State

You can use the Grid State to put the component in add or edit mode programmatically. This process does not use built-in commands. In this case, set the default item values to the InsertedItem property of the GridState object.

var gridState = GridRef.GetState();

gridState.InsertedItem = new Order();
gridState.InsertedItem.Quantity = 10;
gridState.InsertedItem.Received = DateTime.Now;

await GridRef.SetStateAsync(gridState);

See Also

  • Grid CRUD Events
  • Grid State