New to Telerik UI for ASP.NET Core? Download free 30-day trial

Selected Rows Relations in Hierarchical Grids

Environment

Product Version 2023.3.1114
Product Telerik UI for ASP.NET Core Grid

Description

I have a parent and a child Grid configured with a Detail Template. When the user selects a row in the child Grid, the checkbox of the parent row must become indeterminate. If all child rows are selected, the parent row must be selected, as well.

Solution

  1. Subscribe to the Change Event of both Grids.

        @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
                .Name("grid")
                .ClientDetailTemplateId("template")
                //omitted for brevity
                .Events(events => events.Change("onChangeParent"))
        )
    
        <script id="template" type="text/kendo-tmpl">
            @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
                .Name("grid_#=EmployeeID#")
                //omitted for brevity 
                .Events(e=>e.Change("onChangeChild"))
                .ToClientTemplate()
                )
        </script>
    
  2. Within the event handler of the parent Grid, get all selected rows by using the select() method, iterate the rows, access their dataItems, and use the row Id to select the child Grid of each selected row. Then select all child Grid rows.

        function onChangeParent(e){
            var selected = e.sender.select();
            selected.each((ind,row)=>{
                var dataItem = e.sender.dataItem(row);
                var childGrid = $("#grid_"+dataItem.EmployeeID).data("kendoGrid");
                childGrid.select("tr")
            })
        }
    
  3. Within the event handler of the child Grid, get the parent row with jQuery. Then, use the following logic to either select the parent's checkbox, to make it indeterminate or to deselect it based on the number of rows selected in the child.

        function onChangeChild(e){
            var masterRow = $(e.sender.element).closest(".k-detail-row").siblings(".k-master-row").first();
            var checkbox = masterRow.find(".k-select-checkbox");
            if(e.sender.select().length==e.sender.items().length){
                checkbox[0].indeterminate=false;
                checkbox.prop("checked",true);
            }else if(e.sender.select().length>0 ){           
                checkbox[0].indeterminate=true;
            }else{
                checkbox[0].indeterminate=false;
                checkbox.prop("checked",false);
            }
        }
    

Review the behavior of the suggested approach in this REPL sample.

Notes

The suggested example will work only for detail rows that have been expanded and initialized.

More ASP.NET Core Grid Resources

See Also

In this article