Search code examples
javascriptasp.net-mvckendo-uitelerik

Conditional formatting is possible in Kendo Telerik grid when filtering?


I'd like to change background color of the rows in a Kendo Telerik grid, when applied a filter. I have and ASP.NET Mvc application. Is it possible?


Solution

  • Kendo's Grid has a built in option to change how the TRs are displayed, called rowTemplate. The problem is that when you are using it, you have to deal with the whole row creation:

    columns: [{
        title: "Id",
        field: "Id"
    }],
    rowTemplate: kendo.template($("#grid-template").html()),
    filter: function() {
        rowAlt = 0; // This is a global variable
    }
    

    And the template:

    <script id="grid-template" type="text/x-kendo-template">
    # let filter = $("\#grid").data("kendoGrid").dataSource.filter();
    
    #<tr class='#
    
    if (++rowAlt % 2 == 0) {
        #k-alt #
    }
    
    if (filter != null) {
        #filtered-row#
    }
    
    #'><td>#=data.Id#</td>#
    #<tr>##
    </script>
    

    Demo


    Now, there is another way, which means to customize the grid's styles outside it, as proposed by other users already. It maked the grid's initialization simple and handles the styles after the rows are rendered(in dataBound event):

    filterable: true,
    columns: [{
        title: "Id",
        field: "Id"
    }],
    dataBound: function() {
        window.setTimeout(function() {
            if (this.dataSource.filter()) {
              this.tbody.find("tr").addClass("filtered-row");
            }
        }.bind(this), 1);
    }
    

    Demo

    Note: I'm using setTimeout in the snippet above because sometimes the dataBound event is called before the DOM elements are finished rendering.

    Both examples above I made it added a bg color in the row whenever the grid is filtered, you have to make your conditions based on dataSource.filter() result object, which contains all filter settings.