New to Telerik UI for Blazor? Download free 30-day trial

Add Grid Columns Programmatically

Environment

Product Grid for Blazor

Description

I want to add a custom Grid column programmatically. I would also like to define attributes for the column such as Field, Title, and DisplayFormat.

Solution

You can use the RenderTreeBuilder class to create a GridColumn from the C# portion of the application.

Add a GridColumn from code

@* Use the Render Tree Builder to add a grid column. Click on the Add a column button to see the result *@

    <TelerikButton OnClick="@(() => CustomGridColumnFromCode = AddAGridColumn())">Add a column</TelerikButton>

    <TelerikGrid Data="@MyData" Height="400px"
                 Pageable="true" Sortable="true" Groupable="true"
                 FilterMode="Telerik.Blazor.GridFilterMode.FilterRow"
                 Resizable="true" Reorderable="true"
                 @ref="@GridRef">
        <GridColumns>
            <GridColumn Field="@(nameof(SampleData.Id))" Width="120px" />
            <GridColumn Field="@(nameof(SampleData.Name))" Title="Employee Name" Groupable="false" />
            <GridColumn Field="@(nameof(SampleData.Team))" Title="Team" />
            <GridColumn Field="@(nameof(SampleData.HireDate))" Title="Hire Date" />

            @CustomGridColumnFromCode
        </GridColumns>
    </TelerikGrid>


    @code {
        private TelerikGrid<SampleData> GridRef { get; set; }

        private RenderFragment CustomGridColumnFromCode { get; set; }

        private RenderFragment AddAGridColumn() => builder =>
        {
            builder.OpenComponent(0, typeof(GridColumn));

            builder.AddAttribute(0, "Field", "CustomDateField"); //The Field for the Column
            builder.AddAttribute(1, "Title", "From code behind"); //The Title for the Column
            builder.AddAttribute(2, "DisplayFormat", "{0:dd MMM yy}"); //The DisplayFormat for the Column

            builder.CloseComponent();
        };

        public IEnumerable<SampleData> MyData = Enumerable.Range(1, 30).Select(x => new SampleData
        {
            Id = x,
            Name = "name " + x,
            Team = "team " + x % 5,
            CustomDateField = DateTime.Today.AddDays(x),
            HireDate = DateTime.Now.AddDays(-x).Date
        });

        public class SampleData
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Team { get; set; }
            public DateTime CustomDateField { get; set; }
            public DateTime HireDate { get; set; }
        }
    }
In this article