How to set Kendo UI grid column widths programmatically

时间秒杀一切 提交于 2019-12-04 02:44:41

You need to change grid's width through its element instead of its definition. Kendo grid contains header and content, so you need to change two elements.

Use this code instead

$("#grid-id .k-grid-header-wrap").find("colgroup col").eq(xx).width(yy);
$("#grid-id .k-grid-content").find("colgroup col").eq(xx).width(yy);

Sample

I've ended with this. Dion's solution gave me starting idea about using colgroups, however that solution is limited to not having locked columns, what are in different colgroups.

Also note: I do not want to use grid.setOptions, because its limitations, ruining attached events and header (in case of using ASP MVC helper to render the grid)

function setColumnWidths(grid, options) {
    var lockedCount = 0;
    for (var i = 0; i < options.columns.length; i++) {
        if (options.columns[i].hasOwnProperty('locked')) {
            if (options.columns[i].locked) {
                lockedCount++;
            }
        }
    }

    for (var i = 0; i < options.columns.length; i++) {
        var width = options.columns[i].width;
        grid.columns[i].width = width;
        if (options.columns[i].hasOwnProperty('locked') && options.columns[i].locked) {
            $("#grid .k-grid-header-locked").find("colgroup col").eq(i).width(width);
            $("#grid .k-grid-content-locked").find("colgroup col").eq(i).width(width);

        } else {
            $("#grid .k-grid-header-wrap").find("colgroup col").eq(i-lockedCount).width(width);
            $("#grid .k-grid-content").find("colgroup col").eq(i - lockedCount).width(width);
        }
    }
    // Hack to refresh grid visual state
    grid.reorderColumn(1, grid.columns[0]);
    grid.reorderColumn(1, grid.columns[0]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!