Set Default Values for New Grid Rows
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
orJan 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.
Set default values inline
public class Order
{
public int Quantity { get; set; } = 10;
public DateTime Received { get; set; } = DateTime.Now;
}
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.
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.
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);