Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
12679
Autosizing columns in WebDataGrid
posted

The column widths of the WebDataGrid may be autosized based on header and cell text width.

In order to autosize column width, the Initialize client side event of the WebDataGrid has to be handled. We can iterate through the columns and check whether the header text is wider than the current width of a column. Below is some sample javascript code of how this can be done.

function _dg_Grid_Initialize(sender, eventArgs) {

 

    if (null == $find(sender.get_id())) { return; }

 

 

    var textWidthChecker = document.getElementById('textWidthChecker');

    

    var grid = $find(sender.get_id());

    var columns = grid.get_columns();

    var row = grid.get_rows().get_row(0);

 

    for (colIdx = 0; colIdx < columns.get_length(); colIdx++) {

        var col = columns.get_column(colIdx);

        textWidthChecker.innerHTML = col.get_headerText();

 

        var cellElement = row.get_cell(colIdx)._element;

        if (!col.get_hidden()) {

 

            // resize based on cell content widths

            if (textWidthChecker.offsetWidth > cellElement.offsetWidth) {

                col.set_width(textWidthChecker.offsetWidth);

            }

                   

            // resize based on header text length

            if (col.get_headerElement().offsetWidth < col.get_headerText().length * 8) {

                   var newWidth = (col.get_headerText().length * 8).toString() + 'px';

                   col.set_width(newWidth);

               }

        }

    }

}

 

 

Similarly, we can also check whether the value of some row cell is too wide to be displayed: