Are you considering only checking the content of the first row in the grid, as shown in your code sample? If so, you can set up a dataBound
handler to hide columns based on this criteria:
dataBound : function (e) {
var grid = e.sender;
var data = e.sender.dataSource.data();
if (data.length > 0) {
$.each(grid.options.columns, function (idx, elem) {
if (!data[0][elem.field]) {
grid.hideColumn(idx);
}
});
}
}
This code snippet executes every time new data is received from the server. However, it currently only checks the content of the first row. You can easily adapt this logic to check all rows. One limitation is that it doesn't hide column titles from the menu.
For a live demonstration, visit: http://jsfiddle.net/OnaBai/XNcmt/67/
UPDATE: To ensure that columns with no data are not displayed and do not appear in the menu, adjust the columns
configuration within the grid setup. Here's an example of how to achieve this dynamically after receiving data:
// Fetch data from the DataSource
ds.fetch(function (d) {
var columns = [];
var definitions = [
{ field: "Id", hidden: true },
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "City" },
{ field: "Position" }
];
$.each(definitions, function(idx, elem) {
if(d.items[0][elem.field]) {
columns.push(elem);
}
});
$("#grid").kendoGrid({
dataSource: d.items,
editable : false,
pageable : true,
columnMenu: true,
columns : columns
}).data("kendoGrid");
});
View this solution in action here: http://jsfiddle.net/OnaBai/XNcmt/69/