Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I autosize the column in SlickGrid?

I want slickgrid to autosize the columns based on the widest content or header text - whichever is wider. In simpler terms, I want it to simulate the default behavior of regular HTML tables when it comes to column sizing. How can I do it in slickgrid?

like image 313
PJ. Avatar asked Jul 22 '11 18:07

PJ.


5 Answers

When constructing your options, you can use forceFitColumns: true

var options = {
    enableCellNavigation: true,
    forceFitColumns: true
};

This will make the columns fill the entire width of your grid div.

like image 55
csigrist Avatar answered Oct 03 '22 04:10

csigrist


The OP is looking for columns to grow to match their content. grid.autosizeColumns() grows the cells to fit the parent container, which is not the same thing.

I have added this feature, and it is about as manual as you might imagine. You loop through the displayed cells and measure each one, saving the widest cell and using that width to set the width of your column. SlickGrid gives you good access to the cells in the viewport, so that works nicely.

The measurement algorithm is your big decision. You may put the content off screen and measure it, as @jay suggests. This works, but it is the slowest method, as it requires a repaint to insert, and a repaint when you remove. There may be ways to optimize. The solution I went with is to measure the width of every letter in the alphabet, as well as other typographic characters we come across, and sum them to generate a width. Yes, this sounds absurd. It has many constraints: The font size must be the same, it doesn't support images, there can't be any line returns, and more. If you can live with the constraints though, you can calculate sizes for a huge grid viewport in <5ms, because the character widths are only measured once.

After you get the sizes of the columns, you assign them to your columns using grid.setColumns().

like image 33
SimplGy Avatar answered Oct 03 '22 05:10

SimplGy


Slickgrid will not support column auto size based on data.You need to write a plugin or fork the slickgrid core to modify.

Here is the link I have created a plugin to handle slickgrid auto size https://github.com/naresh-n/slickgrid-column-data-autosize

like image 35
Naresh Nagabhushanam Avatar answered Oct 03 '22 04:10

Naresh Nagabhushanam


I added this after the grid is drawn and it works fine.

$(window).resize(function() {
var cols = grid.getColumns();
grid.setColumns(cols);
})
like image 32
Kirk Ross Avatar answered Oct 03 '22 04:10

Kirk Ross


You should be able to call the autosizeColumns() method of the grid object.

grid.autosizeColumns();
like image 40
njr101 Avatar answered Oct 03 '22 06:10

njr101