How to change columns set of kendo grid dynamically

user2503696 picture user2503696 · Jun 20, 2013 · Viewed 50k times · Source

I am trying to change the columns collection of my Kendo grid in the below way.

var grid = $("#grid").data("kendoGrid");
$http.get('/api/GetGridColumns')
    .success(function (data) {
        grid.columns = data;                    
    })
    .error(function (data) {
        console.log(data);
    });

This is changing the column collection but not reflecting immediately in my grid. But when I try to perform some actions in the grid (like grouping), then my new column set is appearing.

Please let me know how can I achieve this.

Regards, Dilip Kumar

Answer

Edu Cielo picture Edu Cielo · Jun 3, 2014

You can do it by setting the KendoUI datasource, destroy the grid, and rebuild it

$("#load").click(function () {
        var grid = $("#grid").data("kendoGrid");

    var dataSource = grid.dataSource;

    $.ajax({
        url: "/Home/Load",
        success: function (state) {
            state = JSON.parse(state);

            var options = grid.options;

            options.columns = state.columns;

            options.dataSource.page = state.page;
            options.dataSource.pageSize = state.pageSize;
            options.dataSource.sort = state.sort;
            options.dataSource.filter = state.filter;
            options.dataSource.group = state.group;

            grid.destroy();

            $("#grid")
               .empty()
               .kendoGrid(options);
        }
    });
});

here you can just do this :

var options = grid.options;

options.columns = state.columns;

where you can retrieve the columns in a session or in a db