Column Template
By default, the grid renders the value of the field in the column, as it is provided from the data source. You can change this behavior by using the Template
of the column and add your own content and/or logic to make a string out of the object.
The column template (the <Template>
tag under the column definition) is what the grid uses to show the "view" representation of the cell. This also includes a column that is marked as Editable="false"
and is in edit mode.
If you only want to format numbers, dates, enums, you can do so with the DisplayFormat feature without the need to declare a template.
The example below shows how to:
- set the
Template
(make sure to use the capitalT
, at the time of writing the Visual Studio autocomplete tends to use the lowercaset
which breaks the template logic and does not allow you to access the context) - access the
context
of the model item so you can employ your own logic - set HTML in the column
- use inline or multi-line template
- take the field name from the model
Using cell (column) template
Cell template that renders an image based on model data
<TelerikGrid Data="@MyData" Height="500px">
<GridColumns>
<GridColumn Field="@(nameof(SampleData.ID))" Title="Photo">
<Template>
@{
var employee = context as SampleData;
<img class="rounded" src="@($"/images/{employee.ID}.jpg")" alt="employee photo" />
}
</Template>
</GridColumn>
<GridColumn Field="@(nameof(SampleData.Name))" Title="Employee Name">
<Template>
Employee name is:
<br />
@((context as SampleData).Name)
</Template>
</GridColumn>
<GridColumn Field="HireDate" Title="Hire Date - Default string">
</GridColumn>
<GridColumn Field="HireDate" Title="Hire Date - Custom string">
<Template>
@((context as SampleData).HireDate.ToString("dd MMM yyyy"))
</Template>
</GridColumn>
</GridColumns>
</TelerikGrid>
@code {
public class SampleData
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime HireDate { get; set; }
}
public IEnumerable<SampleData> MyData = Enumerable.Range(1, 50).Select(x => new SampleData
{
ID = x,
Name = "name " + x,
HireDate = DateTime.Now.AddDays(-x)
});
}
The result from the code snippet above