Telerik UI For Blazor: Add Item To Grid In Code

933 views Asked by At

Telerik Grid for Blazor, how to add a row through code. Should be easy, but I cannot find a straightforward answer anywhere. Here's my grid:

                    <TelerikGrid Data=@GridPallets
                                 Height="200px"
                                 FilterMode="@GridFilterMode.None"
                                 Sortable=true
                                 Pageable=true>
                        <GridColumns>
                            <GridColumn Field=@nameof(PalletGridModel.Type) />
                            <GridColumn Field=@nameof(PalletGridModel.Quantity) />
                            <GridColumn Field=@nameof(PalletGridModel.Weight) />
                            <GridColumn Field=@nameof(PalletGridModel.DeliveryCharge) Title="Delivery Charge" />
                            <GridColumn Field=@nameof(PalletGridModel.HubCharge) Title="Hub Charge" />
                        </GridColumns>
                    </TelerikGrid>

Here's some code on the same page to create a new item to add to the grid:

PalletGridModel pgm = new PalletGridModel();

pgm.DeliveryCharge = palletType == "QTR" ? 10 : palletType == "HALF" ? 20 : palletType == "FULL" ? 30 : 40;
pgm.HubCharge = palletType == "QTR" ? 4 : palletType == "HALF" ? 5 : palletType == "FULL" ? 6 : 10;
pgm.Quantity = quantity;
pgm.Type = palletType;
pgm.Weight = weight;

Everything I've tried after that to add that new item to the grid doesn't work - from adding the item to the grid data with a simple list.add(item) to trying to use the grid's update handler - but so far, nothing has worked. Surely something as simple and straightforward as this can't be this difficult?

1

There are 1 answers

0
Graham Laight On

With a bit of help from Telerik, I now have a good answer. Use the ObjectModel:

@using System.Collections.ObjectModel

Set the grid's collection type to observable:

<TelerikGrid Data=@GridPallets ...
public ObservableCollection<Models.PalletGridModel> GridPallets { get; set; }

Have a list for modifying the grid's values:

public List<Models.PalletGridModel> GridSourceData { get; set; } = new List<PalletGridModel>();

Modify the spare list:

PalletGridModel pgm = new PalletGridModel();
{set values}
GridSourceData.Add(pgm);

Set the actual grid source:

GridPallets = new ObservableCollection<Models.PalletGridModel>(GridSourceData);