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

Grid Events

This article explains the events available in the Telerik Grid for Blazor. They are grouped logically.

CUD Events

The OnAdd, OnCreate, OnUpdate and OnDelete events let you get the data item that the user changed so you can transfer the user action to the actual data source.

The OnEdit and OnCancel events let you respond to user actions - when they want to edit an item and when the want to cancel changes on an item they have been editing. You can use them to, for example, prevent editing of certain items based on some condition.

You can read more about the CUD events in the Editing Overview article.

Read Event

In the common case, you provide all the data to the Grid's Data collection and the Grid performs operations like paging, filtering, sorting on it for you. In some cases you may want to do this with your own code (for example, to retrieve only a small number of items in order to improve the backend performance). You can do this by handling the OnRead event where you can perform all the data read operations in the Grid. Read more about the OnRead event fundamentals and check the article about Manual Data Source Operations with the Grid.

State Events

The grid state lets you control through code the aspects of the grid the user can control in the UI - such as filtering, sorting, grouping. The grid provides two events related to the state:

  • OnStateInit - fires when the grid initializes so you can provide a stored version of the grid.

  • OnStateChanged - fires when the user performs an action so you can see what area was changed and, if needed, alter the grid state.

Review the grid state article for more details and examples on how the grid state works and what you can do with it.

Column Events

The Grid columns emit the OnCellRender event, so you can customize each cell separately. Read more and find examples in the Grid Column Events article.

Command Button Click

The command buttons of a grid provide an OnClick event before firing their built-in command (such as opening a row for editing, or adding a new row). You can do this to implement some additional logic and to also handle custom commands - both from a Command Column, and from a Toolbar Button

Export Events

During export, the Grid will fire events like OnBeforeExport and OnAfterExport. They allow you to:

  • Get or modify the columns and their settings;
  • Provide custom data;
  • Cancel the export;
  • Get the final file output;

Read more about them and find code examples in the Grid Export Events article.

OnModelInit

The OnModelInit event fires before editing and adding new item in the component. The event allows you to:

  • bind the component to a class that has no parameterless constructor

  • bind the component to an interface

  • bind the component to an abstract class

To achieve the desired behavior you can provide an instance of the model that the component is bound to in the OnModelInit event handler.

The different use-cases of the OnModelInit event

@* Bind the Grid to a class without a parameterless constructor *@

<TelerikGrid Data="@SampleGridData"
             AutoGenerateColumns="true"
             Pageable="true"
             PageSize="10"
             FilterMode="@GridFilterMode.FilterMenu"
             EditMode="@GridEditMode.Incell"
             OnModelInit="@OnModelInitHandler"
             OnUpdate="@UpdateHandler"
             OnDelete="@DeleteHandler"
             OnCreate="@CreateHandler"
             OnCancel="@CancelHandler">
    <GridColumns>
        <GridAutoGeneratedColumns />
        <GridCommandColumn>
            <GridCommandButton Command="Delete" Icon="@SvgIcon.Trash">Delete</GridCommandButton>
        </GridCommandColumn>
    </GridColumns>
</TelerikGrid>

@code {
    private List<SampleData> SampleGridData { get; set; }

    private SampleData OnModelInitHandler()
    {
        return new SampleData(1, "Sample Text", DateTime.Now);
    }

    async Task UpdateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operations here through your service
        await MyService.Update(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    async Task DeleteHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        await MyService.Delete(item);

        await GenerateSampleData();

        Console.WriteLine("Delete event is fired.");
    }

    async Task CreateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operation here through your service
        await MyService.Create(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    void CancelHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;
    }

    protected override async Task OnInitializedAsync()
    {
        await GenerateSampleData();
    }

    private async Task GenerateSampleData()
    {
        SampleGridData = await MyService.Read();
    }

    public class SampleData
    {
        public int SampleId { get; set; }
        public string SampleText { get; set; }
        public DateTime SampleDate { get; set; }

        public SampleData(int id, string text, DateTime date)
        {
            SampleId = id;
            SampleText = text;
            SampleDate = date;
        }
    }

    public static class MyService
    {
        private static List<SampleData> _data { get; set; } = new List<SampleData>();

        public static async Task Create(SampleData itemToInsert)
        {
            itemToInsert.SampleId = _data.Count + 1;
            _data.Insert(0, itemToInsert);
        }

        public static async Task<List<SampleData>> Read()
        {
            if (_data.Count < 1)
            {
                for (int i = 1; i < 50; i++)
                {
                    _data.Add(new SampleData(i, $"Text {i}", DateTime.Today.AddDays(i)));
                }
            }

            return await Task.FromResult(_data);
        }

        public static async Task Update(SampleData itemToUpdate)
        {
            var index = _data.FindIndex(i => i.SampleId == itemToUpdate.SampleId);
            if (index != -1)
            {
                _data[index] = itemToUpdate;
            }
        }

        public static async Task Delete(SampleData itemToDelete)
        {
            _data.Remove(itemToDelete);
        }
    }
}
@* Bind the Grid to an interface *@

<TelerikGrid Data="@SampleGridData"
             AutoGenerateColumns="true"
             Pageable="true"
             PageSize="10"
             FilterMode="@GridFilterMode.FilterMenu"
             EditMode="@GridEditMode.Incell"
             OnModelInit="@OnModelInitHandler"
             OnUpdate="@UpdateHandler"
             OnDelete="@DeleteHandler"
             OnCreate="@CreateHandler"
             OnCancel="@CancelHandler">
    <GridColumns>
        <GridAutoGeneratedColumns />
        <GridCommandColumn>
            <GridCommandButton Command="Delete" Icon="@SvgIcon.Trash">Delete</GridCommandButton>
        </GridCommandColumn>
    </GridColumns>
</TelerikGrid>

@code {
    private List<ISampleData> SampleGridData { get; set; }

    private SampleData OnModelInitHandler()
    {
        return new SampleData(1, "Sample Text", DateTime.Now);
    }

    async Task UpdateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operations here through your service
        await MyService.Update(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    async Task DeleteHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        await MyService.Delete(item);

        await GenerateSampleData();

        Console.WriteLine("Delete event is fired.");
    }

    async Task CreateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operation here through your service
        await MyService.Create(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    void CancelHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;
    }

    protected override async Task OnInitializedAsync()
    {
        await GenerateSampleData();
    }

    private async Task GenerateSampleData()
    {
        SampleGridData = await MyService.Read();
    }

    public interface ISampleData
    {
        public int SampleId { get; set; }
        public string SampleText { get; set; }
    }

    public class SampleData : ISampleData
    {
        public int SampleId { get; set; }
        public string SampleText { get; set; }
        public DateTime SampleDate { get; set; }

        public SampleData(int id, string text, DateTime date)
        {
            SampleId = id;
            SampleText = text;
            SampleDate = date;
        }
    }

    public static class MyService
    {
        private static List<ISampleData> _data { get; set; } = new List<ISampleData>();

        public static async Task Create(SampleData itemToInsert)
        {
            itemToInsert.SampleId = _data.Count + 1;
            _data.Insert(0, itemToInsert);
        }

        public static async Task<List<ISampleData>> Read()
        {
            if (_data.Count < 1)
            {
                for (int i = 1; i < 50; i++)
                {
                    _data.Add(new SampleData(i, $"Text {i}", DateTime.Today.AddDays(i)));
                }
            }

            return await Task.FromResult(_data);
        }

        public static async Task Update(SampleData itemToUpdate)
        {
            var index = _data.FindIndex(i => i.SampleId == itemToUpdate.SampleId);
            if (index != -1)
            {
                _data[index] = itemToUpdate;
            }
        }

        public static async Task Delete(SampleData itemToDelete)
        {
            _data.Remove(itemToDelete);
        }
    }
}
@* Bind the Grid to an abstract class *@

<TelerikGrid Data="@SampleGridData"
             AutoGenerateColumns="true"
             Pageable="true"
             PageSize="10"
             FilterMode="@GridFilterMode.FilterMenu"
             EditMode="@GridEditMode.Incell"
             OnModelInit="@OnModelInitHandler"
             OnUpdate="@UpdateHandler"
             OnDelete="@DeleteHandler"
             OnCreate="@CreateHandler"
             OnCancel="@CancelHandler">
    <GridColumns>
        <GridAutoGeneratedColumns />
        <GridCommandColumn>
            <GridCommandButton Command="Delete" Icon="@SvgIcon.Trash">Delete</GridCommandButton>
        </GridCommandColumn>
    </GridColumns>
</TelerikGrid>

@code {
    private List<SampleDataBase> SampleGridData { get; set; }

    private SampleData OnModelInitHandler()
    {
        return new SampleData(1, "Sample Text", DateTime.Now);
    }

    async Task UpdateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operations here through your service
        await MyService.Update(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    async Task DeleteHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        await MyService.Delete(item);

        await GenerateSampleData();

        Console.WriteLine("Delete event is fired.");
    }

    async Task CreateHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;

        // perform actual data source operation here through your service
        await MyService.Create(item);

        // update the local view-model data with the service data
        await GenerateSampleData();
    }

    void CancelHandler(GridCommandEventArgs args)
    {
        SampleData item = (SampleData)args.Item;
    }

    protected override async Task OnInitializedAsync()
    {
        await GenerateSampleData();
    }

    private async Task GenerateSampleData()
    {
        SampleGridData = await MyService.Read();
    }

    public abstract class SampleDataBase
    {
        public int SampleId { get; set; }
        public string SampleText { get; set; }
    }

    public class SampleData : SampleDataBase
    {
        public DateTime SampleDate { get; set; }

        public SampleData(int id, string text, DateTime date)
        {
            SampleId = id;
            SampleText = text;
            SampleDate = date;
        }
    }

    public static class MyService
    {
        private static List<SampleDataBase> _data { get; set; } = new List<SampleDataBase>();

        public static async Task Create(SampleData itemToInsert)
        {
            itemToInsert.SampleId = _data.Count + 1;
            _data.Insert(0, itemToInsert);
        }

        public static async Task<List<SampleDataBase>> Read()
        {
            if (_data.Count < 1)
            {
                for (int i = 1; i < 50; i++)
                {
                    _data.Add(new SampleData(i, $"Text {i}", DateTime.Today.AddDays(i)));
                }
            }

            return await Task.FromResult(_data);
        }

        public static async Task Update(SampleData itemToUpdate)
        {
            var index = _data.FindIndex(i => i.SampleId == itemToUpdate.SampleId);
            if (index != -1)
            {
                _data[index] = itemToUpdate;
            }
        }

        public static async Task Delete(SampleData itemToDelete)
        {
            _data.Remove(itemToDelete);
        }
    }
}

OnRowClick

The OnRowClick event fires when the user:

  • Clicks or taps on a data row.
  • Hits Enter while the row has focus. This scenario requires enabled keyboard navigation (Navigable="true").

The event does not fire when the user:

  • Clicks or taps on a command button;
  • Selects a row via the built-in checkbox column;
  • Expands or collapses the hierarchy;
  • When the clicked row is in edit mode.

OnRowClick event fires before selection.

The OnRowClick event handler receives a GridRowClickEventArgs argument, which has the following properties.

Property Type Description
EventArgs EventArgs This object maps to MouseEventArgs or KeyboardEventArgs depending on the user action.
Field string The Field parameter of the clicked column.
Item object The data item. Cast the object to your model type to access its members.
ShouldRender bool Sets if the component will re-render after the event via StateHasChanged() call. This can be useful if you need to change the component parameters or state during the event execution, and especially if you need to execute async logic in the event handler.

Use the OnRowClick event to load data on demand based on the clicked row

@* Use the OnRowClick event to load data on demand based on the clicked row *@

There is a deliberate delay in the data loading to showcase the async nature of the event

<TelerikGrid Data="@MyData"
             Height="400px"
             Width="700px"
             Pageable="true"
             OnRowClick="@OnRowClickHandler"
             SelectionMode="@GridSelectionMode.Single"
             @bind-SelectedItems="@SelectedItems">
    <GridColumns>
        <GridColumn Field="@(nameof(SampleData.Id))" Width="120px" />
        <GridColumn Field="@(nameof(SampleData.Name))" Title="Employee Name" />
        <GridColumn Field="@(nameof(SampleData.Team))" Title="Team" />
        <GridColumn Field="@(nameof(SampleData.HireDate))" Title="Hire Date" />
    </GridColumns>
</TelerikGrid>

@if (ProjectData.Any())
{
    <br />
    <TelerikGrid Data="@ProjectData" AutoGenerateColumns="true"
                 Pageable="true" PageSize="4" Width="700px">
    </TelerikGrid>
}

@code {
    // enable single row selection to showcase the clicked row to the user. Not mandatory
    public IEnumerable<SampleData> SelectedItems { get; set; } = Enumerable.Empty<SampleData>();

    // data that will be loaded on demand for the next components - another grid in this sample
    public List<ProjectModel> ProjectData { get; set; } = new List<ProjectModel>();

    async Task OnRowClickHandler(GridRowClickEventArgs args)
    {
        var model = args.Item as SampleData;

        ProjectData = await GetProjectData(model.Id);

        if (args.EventArgs is KeyboardEventArgs keyboardEventArgs)
        {
            Console.WriteLine($"The user pressed {keyboardEventArgs.Key} on row {model.Name} and column {args.Field}.");
        }
        else if (args.EventArgs is MouseEventArgs mouseEventArgs)
        {
            Console.WriteLine($"The user clicked {mouseEventArgs.ClientX} {mouseEventArgs.ClientY} on row {model.Name} and column {args.Field}.");
        }
    }

    async Task<List<ProjectModel>> GetProjectData(int id)
    {
        await Task.Delay(500); // simulate loading data from a service, remove from a real app

        ProjectData = new List<ProjectModel>()
        {
            new ProjectModel()
            {
                ProjectManagerId = id,
                ProjectName = $"Project name {id}",
                DueDate = DateTime.Today.AddDays(-id),
                isActive = id % 2 == 0 ? true : false
            }
        };
        return await Task.FromResult(ProjectData);
    }

    public IEnumerable<SampleData> MyData = Enumerable.Range(1, 30).Select(x => new SampleData
    {
        Id = x,
        Name = "name " + x,
        Team = "team " + x % 5,
        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 HireDate { get; set; }
    }

    public class ProjectModel
    {
        public int ProjectManagerId { get; set; }
        public string ProjectName { get; set; }
        public DateTime DueDate { get; set; }
        public bool isActive { get; set; }
    }
}

The result from the code snippet above

OnRowClick example

OnRowDoubleClick

The OnRowDoubleClick event fires when the user double-clicks or double-taps on a data row.

The event does not fire when the user:

  • Clicks or taps on a command button;
  • Selects a row via the built-in checkbox column;
  • Expands or collapses the hierarchy;
  • When the clicked row is in edit mode.

OnRowDoubleClick event fires before selection.

The OnRowDoubleClick event handler receives a GridRowClickEventArgs argument, which has the following properties.

Property Type Description
EventArgs EventArgs This object maps to MouseEventArgs or KeyboardEventArgs depending on the user action.
Field string The Field parameter of the clicked column.
Item object The data item. Cast the object to your model type to access its members.
ShouldRender bool Sets if the component will re-render after the event via StateHasChanged() call. This can be useful if you need to change the component parameters or state during the event execution, and especially if you need to execute async logic in the event handler.

Use the OnRowDoubleClick event to receive information on the clicked row

@* Use the OnRowDoubleClick event to receive information on the row the user clicked on *@

<TelerikGrid Data="@MyData"
             Height="400px"
             Width="700px"
             Pageable="true"
             OnRowDoubleClick="@OnRowDoubleClickHandler">
    <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" />
    </GridColumns>
</TelerikGrid>

@if (!String.IsNullOrEmpty(logger))
{
    <div>
        @logger
    </div>
}

@code {
    string logger = String.Empty;

    void OnRowDoubleClickHandler(GridRowClickEventArgs args)
    {
        var model = args.Item as SampleData;

        logger = $"Double clicked on {model.Name}";

        if (args.EventArgs is KeyboardEventArgs keyboardEventArgs)
        {
            Console.WriteLine($"The user pressed {keyboardEventArgs.Key} on row {model.Name} and column {args.Field}.");
        }
        else if (args.EventArgs is MouseEventArgs mouseEventArgs)
        {
            Console.WriteLine($"The user clicked {mouseEventArgs.ClientX} {mouseEventArgs.ClientY} on row {model.Name} and column {args.Field}.");
        }

    }

    public IEnumerable<SampleData> MyData = Enumerable.Range(1, 30).Select(x => new SampleData
    {
        Id = x,
        Name = "name " + x,
        Team = "team " + x % 5,
        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 HireDate { get; set; }
    }
}

OnRowContextMenu

The OnRowContextMenu event fires when the user:

  • Right-clicks or taps-and-holds a data row;
  • Hits the context menu keyboard button while the row has focus. This scenario requires enabled keyboard navigation (Navigable="true").

Use OnRowContextMenu to integrate the Context menu with the table rows.

The OnRowContextMenu event handler receives a GridRowClickEventArgs argument, which has the following properties.

Property Type Description
EventArgs EventArgs This object maps to MouseEventArgs or KeyboardEventArgs depending on the user action.
Field string The Field parameter of the clicked column.
Item object The data item. Cast the object to your model type to access its members.
ShouldRender bool Sets if the component will re-render after the event via StateHasChanged() call. This can be useful if you need to change the component parameters or state during the event execution, and especially if you need to execute async logic in the event handler.

Use the Grid OnRowContextMenu event and get the data model

@* Get the row model from a context menu action (right click/long tap) *@

<TelerikGrid Data="@MyData"
             Pageable="true"
             PageSize="6"
             OnRowContextMenu="@OnRowContextMenuHandler">
    <GridColumns>
        <GridColumn Field="@(nameof(SampleData.Id))" Width="120px" />
        <GridColumn Field="@(nameof(SampleData.Name))" Title="Employee Name" />
        <GridColumn Field="@(nameof(SampleData.Team))" Title="Team" />
        <GridColumn Field="@(nameof(SampleData.HireDate))" Title="Hire Date" />
    </GridColumns>
</TelerikGrid>

<br />

@logger

@code {
    void OnRowContextMenuHandler(GridRowClickEventArgs args)
    {
        SampleData model = args.Item as SampleData;

        logger = $"OnRowContextMenu event fired from right clicking on {model.Name}";

        if (args.EventArgs is KeyboardEventArgs keyboardEventArgs)
        {
            Console.WriteLine($"The user pressed {keyboardEventArgs.Key} on row {model.Name} and column {args.Field}.");
        }
        else if (args.EventArgs is MouseEventArgs mouseEventArgs)
        {
            Console.WriteLine($"The user clicked {mouseEventArgs.ClientX} {mouseEventArgs.ClientY} on row {model.Name} and column {args.Field}.");
        }
    }

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

    public string logger { get; set; } = String.Empty;


    public class SampleData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Team { get; set; }
        public DateTime HireDate { get; set; }
    }
}

OnRowExpand

The OnRowExpand event fires as a response to the user expanding the DetailTemplate of the Grid.

The event handler receives a GridRowExpandEventArgs object which provides the model of the clicked row in the Item field that you can cast to your model type.

If you set the ShouldRender field of the event arguments to true, the component will re-render after the event (it will call StateHasChanged()). This can be useful if you need to change its parameters or state during the event execution and especially if you need to execute async logic in the event handler.

Use the OnRowExpand event to load detailed data on demand. Another approach can be found on our public github repository.

@* Load data on demand for the expanded detail row.  *@

<TelerikGrid Data="salesTeamMembers"
             OnRowExpand="@OnRowExpandHandler">
    <DetailTemplate>
        @{
            var employee = context as MainModel;
            <TelerikGrid Data="employee.Orders" Pageable="true" PageSize="5">
                <GridColumns>
                    <GridColumn Field="OrderId"></GridColumn>
                    <GridColumn Field="DealSize"></GridColumn>
                </GridColumns>
            </TelerikGrid>
        }
    </DetailTemplate>
    <GridColumns>
        <GridColumn Field="Id"></GridColumn>
        <GridColumn Field="Name"></GridColumn>
    </GridColumns>
</TelerikGrid>

@code {
    async Task OnRowExpandHandler(GridRowExpandEventArgs args)
    {
        MainModel item = args.Item as MainModel;

        if(item.Orders == null)
        {
            item.Orders = await GenerateOrdersData(item.Id);
        }
    }

    async Task<List<DetailsModel>> GenerateOrdersData(int id)
    {
        var data = new List<DetailsModel>()
        {
            new DetailsModel()
            {
                OrderId = id,
                DealSize = id * 1234,
            }
        };

        return await Task.FromResult(data);
    }

    List<MainModel> salesTeamMembers { get; set; }

    protected override void OnInitialized()
    {
        salesTeamMembers = GenerateData();
    }

    private List<MainModel> GenerateData()
    {
        List<MainModel> data = new List<MainModel>();
        for (int i = 1; i <= 5; i++)
        {
            MainModel mdl = new MainModel { Id = i, Name = $"Name {i}" };
            data.Add(mdl);
        }
        return data;
    }

    public class MainModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<DetailsModel> Orders { get; set; }
    }

    public class DetailsModel
    {
        public int OrderId { get; set; }
        public double DealSize { get; set; }
    }
}

OnRowCollapse

The OnRowCollapse event fires as a response to the user collapsing the DetailTemplate of the Grid.

The event handler receives a GridRowCollapseEventArgs object which provides the model of the clicked row in the Item field that you can cast to your model type.

If you set the ShouldRender field of the event arguments to true, the component will re-render after the event (it will call StateHasChanged()). This can be useful if you need to change its parameters or state during the event execution and especially if you need to execute async logic in the event handler.

Use the OnRowCollapse event to get the Id of the collapsed row from the data model

@* Get the Id of the collapsed row *@

<TelerikGrid Data="salesTeamMembers"
             OnRowCollapse="@OnRowCollapseHandler">
    <DetailTemplate>
        @{
            var employee = context as MainModel;
            <TelerikGrid Data="employee.Orders" Pageable="true" PageSize="5">
                <GridColumns>
                    <GridColumn Field="OrderId"></GridColumn>
                    <GridColumn Field="DealSize"></GridColumn>
                </GridColumns>
            </TelerikGrid>
        }
    </DetailTemplate>
    <GridColumns>
        <GridColumn Field="Id"></GridColumn>
        <GridColumn Field="Name"></GridColumn>
    </GridColumns>
</TelerikGrid>

<br />

@logger

@code {
    void OnRowCollapseHandler(GridRowCollapseEventArgs args)
    {
        MainModel item = args.Item as MainModel;
        logger = $"The collapsed row is with id: {item.Id}";
    }

    public string logger { get; set; } = String.Empty;
    List<MainModel> salesTeamMembers { get; set; }

    protected override void OnInitialized()
    {
        salesTeamMembers = GenerateData();
    }

    private List<MainModel> GenerateData()
    {
        List<MainModel> data = new List<MainModel>();
        for (int i = 0; i < 5; i++)
        {
            MainModel mdl = new MainModel { Id = i, Name = $"Name {i}" };
            mdl.Orders = Enumerable.Range(1, 15).Select(x => new DetailsModel { OrderId = x, DealSize = x ^ i }).ToList();
            data.Add(mdl);
        }
        return data;
    }

    public class MainModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<DetailsModel> Orders { get; set; }
    }

    public class DetailsModel
    {
        public int OrderId { get; set; }
        public double DealSize { get; set; }
    }
}

OnRowRender

This event fires when each Grid row renders. This can happen in the following cases:

  • Initial Grid data binding and subsequent data operations (paging, sorting, etc.).
  • A command button is clicked. This includes entering and exiting edit mode, but also custom commands.
  • During typing in edit mode, but only if the column has an EditorTemplate.
  • A child component inside a column Template fires an EventCallback.

OnRowRender receives an argument of type GridRowRenderEventArgs which exposes the following fields:

  • Item - an object you can cast to your model class to obtain the current data item.
  • Class - the custom CSS class that will be applied to the table row.

Use the OnRowRender event to apply custom styles to Grid rows based on certain condition

@* Conditional styling/formatting for rows (including locked/frozen columns). *@

<style>
    /*the following selectors target the locked/frozen columns*/
    /*===*/
    .k-grid .k-master-row.myCustomRowFormatting .k-grid-content-sticky,
    .k-grid .k-master-row.myCustomRowFormatting.k-alt .k-grid-content-sticky
    /*===*/ {
        background-color: inherit;
    }

    .k-grid .k-master-row.myCustomRowFormatting:hover {
        background-color: red !important;
    }

    .k-grid .k-master-row.myCustomRowFormatting {
        background-color: #90EE90;
    }
</style>

<TelerikGrid Data="@MyData"
             Height="446px"
             Pageable="true"
             Width="450px"
             OnRowRender="@OnRowRenderHandler">
    <GridColumns>
        <GridColumn Field="@(nameof(SampleData.Id))" Width="120px" Locked="true" />
        <GridColumn Field="@(nameof(SampleData.Name))" Width="200px" Title="Employee Name" />
        <GridColumn Field="@(nameof(SampleData.Team))" Width="200px" Title="Team" />
    </GridColumns>
</TelerikGrid>

@code {
    void OnRowRenderHandler(GridRowRenderEventArgs args)
    {
        var item = args.Item as SampleData;

        //conditional applying Class
        if (item.Name.Contains("5") || item.Name.Contains("6"))
        {
            args.Class = "myCustomRowFormatting";
        }
        if (item.Id < 2)
        {
            args.Class = "myCustomRowFormatting";
        }
    }

    public IEnumerable<SampleData> MyData = Enumerable.Range(1, 30).Select(x => new SampleData
        {
            Id = x,
            Name = "name " + x,
            Team = "team " + x % 5
        });

    public class SampleData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Team { get; set; }
    }
}

OnRowDrop

The OnRowDrop event fires when the user drags and drops rows in the grid or between grids. You can read more on setting it up and using the grid row dragging feature in the Row Drag and Drop article.

PageChanged

The event fires when the user pages the grid.

Handle the PageChanged event to know when the user changes the page

@result

<TelerikGrid Data="@MyData" Pageable="true" PageSize="30"
    PageChanged="@PageChangedHandler" Height="300px">
    <GridColumns>
        <GridColumn Field="ID"></GridColumn>
        <GridColumn Field="TheName" Title="Employee Name"></GridColumn>
    </GridColumns>
</TelerikGrid>

@code {
    string result { get; set; }
    async Task PageChangedHandler(int currPage)
    {
        result = $"the user is now on page {currPage}. Note - the indexes are 1-based, not 0-based";
    }

    public IEnumerable<object> MyData = Enumerable.Range(1, 150).Select(x => new { ID = x, TheName = "name " + x });
}

One-way binding of the Page parameter should be used with the PageChanged event to keep the view-model in sync

@* Set initial page index, and keep it updated with the grid state to prevent it from resetting the grid page index on re-renders *@

<TelerikGrid Data="@MyData" Pageable="true" PageSize="30" Height="300px"
             PageChanged="@PageChangedHandler" Page="@PageIndex">
    <GridColumns>
        <GridColumn Field="ID"></GridColumn>
        <GridColumn Field="TheName" Title="Employee Name"></GridColumn>
    </GridColumns>
</TelerikGrid>

@code {
    int PageIndex { get; set; } = 2;
    async Task PageChangedHandler(int currPage)
    {
        PageIndex = currPage;
        // when using one-way binding for the Page parametr, make sure to update it in the PageChanged event
    }

    public IEnumerable<object> MyData = Enumerable.Range(1, 150).Select(x => new { ID = x, TheName = "name " + x });
}

PageSizeChanged

The PageSizeChanged event fires when the user changes the page size via the pager DropDownList. The existence of this event also ensures that the Grid PageSize attribute supports two-way binding.

If the user selects the "All" option from the page size DropDownList, the PageSizeChanged event will receive the total item count as an argument.

Make sure to update the current page size when using the event.

Handle PageSizeChanged

<TelerikGrid
            Data="@MyData"
            Pageable="true"
            PageSize="@PageSize"
            @bind-Page="@CurrentPage"
            PageSizeChanged="@PageSizeChangedHandler">
    <GridSettings>
        <GridPagerSettings PageSizes="@PageSizes" />
    </GridSettings>
    <GridColumns>
        <GridColumn Field="ID"></GridColumn>
        <GridColumn Field="TheName" Title="Employee Name"></GridColumn>
    </GridColumns>
</TelerikGrid>

@code {
    public IEnumerable<object> MyData = Enumerable.Range(1, 50).Select(x => new { ID = x, TheName = "name " + x });

    int PageSize { get; set; } = 15;
    int CurrentPage { get; set; } = 3;

    protected List<int?> PageSizes { get; set; } = new List<int?> { 15, 30, null };

    void PageSizeChangedHandler(int newPageSize)
    {
        PageSize = newPageSize;
    }
}

SelectedItemsChanged

Fires when row selection is enabled and the user selects or deselects one row or multiple rows, depending on the selection mode.

Visit the Grid Row Selection article to see an example.

SelectedCellsChanged

Fires when cell selection is enabled and the user selects or deselects one cell or multiple cells, depending on the selection mode.

Visit the Grid Cell Selection article to see an example.

See Also

In this article