Search code examples
csskendo-uikendo-gridkendo-asp.net-mvc

Is there any way to automatically adjust grid column width after show/hide a column in kendo-ui grid?


I'm using the kendo-UI grid for displaying some data from my database. I have a set of predefined columns and some of them are visible/hidden by default.

Each column is set to a specific width based on the content and UI requirements and this cannot be set to auto.

There is an option for the user to show or hide columns based on their preferences. The problem is if the user hides a column, it leaves an empty space there. Is there any way to fill up the empty space( like evenly distributing the width of the hidden column to all other visible columns)


Solution

  • I have found a work-around to fix my issue. I have written a custom function to adjust the width of each column on ColumnHide and ColumnShow events of kendo-grid.

    function AdjustColumnWidth() {
        var grid = $("#MyGrid").data("kendoGrid");
        var columns = $("#MyGrid").data("kendoGrid").columns;
        var totalWidth = $('#MyGrid').width();// current width of the grid;
        var visibleColumnsWidth = 0;
        var visibleColumnsCount = 0;
    
        var visibleColumnsWidthAll = [70];//width for first column-this column will be shown always.
        $.each(columns, function (index) {
            if (!this.hidden) {
                if (grid.table[0].rows.length)
                {
                    if (typeof grid.table[0].rows[0].cells[index]!="undefined")
                    {
                        visibleColumnsWidth += grid.table[0].rows[0].cells[index].offsetWidth;
                        visibleColumnsCount += 1;
                        if (index > 0) {
                            visibleColumnsWidthAll.push(grid.table[0].rows[0].cells[index].offsetWidth);
                        }
                    }
                }
            }
        });
        if (visibleColumnsWidth < totalWidth) {
            var diff = totalWidth - visibleColumnsWidth;
            var toAdd = diff / (visibleColumnsCount - 1);
            var tableCol = 1;
            $.each(columns, function (i) {
                if (!this.hidden && i != 0) {
                    $("#MyGrid .k-grid-header-wrap").find("colgroup col").eq(tableCol).width(visibleColumnsWidthAll[tableCol] + toAdd);
                    $("#MyGrid .k-grid-content").find("colgroup col").eq(tableCol).width(visibleColumnsWidthAll[tableCol] + toAdd);
                    tableCol += 1;
                }
            });
        }
    }
    

    And assigned called this function on column show/hide

    .Events(ev => ev.ColumnHide("AdjustColumnWidth").ColumnShow("AdjustColumnWidth"))