Databinding in Blazor Teleric Grid


Recently I was doing POC demo with Telerik Blazor Grid. It is very powerful and user friendly to developer.

Here is the complete code snippet for data binding in grid

@page "/grid"
<h3>GridDemo</h3>

<TelerikGrid Data="@GridData" SelectionMode="@selectionMode"
             Pageable="true" @bind-SelectedItems="@SelectedItems"
             Sortable="true"
             FilterMode="@GridFilterMode.FilterRow">
    <GridColumns>
        <GridCheckboxColumn SelectAll="@ShowSelectAll"></GridCheckboxColumn>
        <GridColumn Field="Name" Title="Product Name" />
        <GridColumn Field="Price" />
        <GridColumn Field="@(nameof(Product.Released))" />
        <GridColumn Field="@(nameof(Product.Discontinued))" />
    </GridColumns>
</TelerikGrid>
<h2>Selected Items:</h2>
<ul>
    @foreach (Product product in SelectedItems)
    {
        <li>
            @product.Name 
        </li>
    }
</ul>

@code {
    GridSelectionMode selectionMode { get; set; } = GridSelectionMode.Multiple;
    List<Product> GridData { get; set; }
    bool ShowSelectAll => selectionMode == GridSelectionMode.Multiple;
    public IEnumerable<Product> SelectedItems { get; set; } = new List<Product>();

    protected override void OnInitialized()
    {
        GridData = Enumerable.Range(1, 30).Select(x => new Product
            {
                Id = x,
                Name = "Product name " + x,
                Price = (decimal)(x * 3.14),
                Released = DateTime.Now.AddMonths(-x).Date,
                Discontinued = x % 5 == 0
            }).ToList();

        base.OnInitialized();
    }

    void ClearSelection(ChangeEventArgs e)
    {
        Enum.TryParse(e.Value.ToString(), out GridSelectionMode chosenMode);
        selectionMode = chosenMode;
        if (chosenMode == GridSelectionMode.Single)
        {
            Product selectedItem = null;
            if (SelectedItems.Count() > 0)
            {
                selectedItem = SelectedItems.Last();
            }
            var TempItems = new List<Product>();
            if (selectedItem != null)
            {
                TempItems.Add(selectedItem);
            }
            SelectedItems = TempItems.AsEnumerable<Product>();
        }
    }
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime Released { get; set; }
        public bool Discontinued { get; set; }
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.