Simple Row Coloring in a KendoUI Grid

Published on Friday, September 12, 2014

So you want to color the rows of your KendoUI grid based on the grid data. This is one of those problems that seems like it should be really simple, but if you search the Internet you'll turn up a bunch of convoluted answers. Most of the recommendations relate to row templates. That's fine if you want to completely restyle the grid rows, but just changing the background color shouldn't be so hard. Thankfully, there is a better way.

This approach will rely on a DataBound JavaScript handler to iterate the rows of the grid post-binding, find the ones that meet your conditions, and set a CSS class on them. The first step is to add the event handler to your grid. If you're using the ASP.NET MVC wrapper it looks like .Events(e => e.DataBound("dataBound")). Then once you've registered the DataBound event, add a JavaScript handler that looks like this:

<script>
function dataBound(e) {
    var grid = $("#grid").data("kendoGrid");
    var gridData = grid.dataSource.view();

    for (var i = 0; i < gridData.length; i++) {
        if (gridData[i].SomeProperty == SomeValue) {
            grid.table.find("tr[data-uid='" + gridData[i].uid + "']").addClass("highlighted-row");
        }
    }
}
</script>

You'll also want to make sure you've got the CSS class declared somewhere (either at the top of the page or in a common CSS file). It might look something like this, which includes darkening the highlighted rows when using banding:

.highlighted-row {
	background-color: #eeffee;
}
.highlighted-row.k-alt {
	background-color: #ccffcc;
}
comments powered by Disqus