While working on a recent project I came across a need to sum a specific column of the Kendo UI Grid in my application after it loaded. Specifically, I had a grid where one column of each row was the “Percent of Total”. What the client requested, was that a message be displayed at the top of the screen whenever the sum of that column in all the rows of the grid did not equal 100%.
My first thought, was that I would handle this server side. I could calculate the sum before I ever sent the data to the view. Drop that sum in ViewData and I would be off to the races.
The problem with this approach is that in this project I was utilizing the excellent inline edit capabilities of the Kendo UI Grid. This meant that the user could add a new row without the screen refreshing. Without that server round trip, I could not be sure what I was showing the user was correct. I needed something client side!
Here was my solution:
- Place a div at the top of the screen to hold the message, hidden.
- If the calculation doesn’t sum to 100% then show the message.
First, place the message at the top of the screen but style it so that it is not shown.
Second, I took advantage of one of the many events available on the Kendo UI Grid. Specifically, I used the dataBound event. The documentation for the Kendo Grid has this to say about when this event is fired.
“Fired when the widget is bound to data from its data source.”
This is not very helpful, in my opinion. This event actually gets fired after the grid loads its data. If you need to take action immediately before, then you should look at the dataBinding event instead.
Using Events in Kendo grid is super easy.
First, use a standard JQuery selector to grab the Grid. When using the selector make sure you use the same name you used in .Name() when creating your grid. In my example I used the ^= (Attribute Starts With) selector, even though it is not really needed here. I often have lots of sub-grids and that is where the starts with comes in handy.
Once you have your grid, we need to grab the datasource and loop through each record.
The rest of the function is simply to do the calculation and show/hide our message.
This technique works well on non-paginated grids, as the datasource object the grid returns you only has the actual data that is visible on the screen for performance reasons. If you needed a paginated grid, you could hook into the same event and make an Ajax call to the server to get the total.