New to Telerik UI for BlazorStart a free 30-day trial

Setting default values in new row

Environment

ProductGrid for Blazor

Description

Is there any way to default the values that are used when I create a new row?

So for example, I have a row where I want to default a date to Jan 1st of the following year. However, when I add the row, it adds nulls to all fields and the date shows up as 1 Jan 1900 and there's a lot of fiddly clicking to set the right date.

Or, if the field is not nullable it would default to a zero or to a Jan 01 in the year 0001.

Solution

There are two ways to set default values in a new row:

Set them in the default constructor of the model class.

How to set default values in a new grid row

C#
    public class SampleData
    {
        public SampleData()
        {
            // to set default values in the grid, use the default constructor of the model
            HireDate = DateTime.Now.AddDays(14);
            Salary = 1000;
        }

        public int ID { get; set; }
        public string Name { get; set; }

        public DateTime HireDate { get; set; }
        public decimal Salary { get; set; }
    }

Use the grid state

You can use the grid state to put the grid in insert/edit mode without the built-in "Add" command. You can add a button (your own or a GridCommandButton but with a custom command name) to the toolbar, and in its OnClick event you can set the InsertedItem of the grid state as desired.

You can find an example of this in the Initiate Editing or Inserting of an Item example.