Demo - Auto-Size Rows

by Joel Parks

HTML

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.wijmo.com/5.latest/styles/wijmo.min.css">
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.input.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.grid.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.grid.filter.min.js"></script>
<div class="container">

  <h1>
    Auto-Size Rows
  </h1>
  <p>
    This grid automatically resizes rows to fit their content.
    It does this by calling the <b>autoSizeRows</b> method
    in response to events that affect the content size.</p>
  <div id="theGrid"></div>
</div>

CSS

.wj-flexgrid {
  max-height: 300px;
}

JavaScript

onload = function() {

  // create some random data
  var countries = 'Austria,Belgium,Canada,Denmark,Estonia,Finland,Germany,Hungary,Ireland,Japan,Korea,Lebanon,Mexico,Norway,Portugal,Qatar,Romania,Spain,Turkey,Ukraine,Venezuela,Zaire'.split(',');
  var data = [];
  for (var i = 0; i < 500; i++) {
    data.push({
    	id: i,
      countries: getCountries(),
      sales: Math.random() * 10000,
      expenses: Math.random() * 5000
    });
  }
  function getCountries() {
  	var c = [];
    var cnt = Math.round(Math.random() * 8) + 1;
    var start = Math.round(Math.random() * countries.length);
    for (var i = 0; i < cnt; i++) {
    	c.push(countries[(i + start) % countries.length]);
    }
    return c.join(', ');
  }

  // show the data in a grid with fixed height
  var theGrid = new wijmo.grid.FlexGrid('#theGrid', {
  	autoGenerateColumns: false,
    columns: [
    	{ binding: 'id', header: 'ID', width: 60, isReadOnly: true },
    	{ binding: 'countries', header: 'Countries', width: '*', wordWrap: true },
    	{ binding: 'sales', header: 'Sales' },
    	{ binding: 'expenses', header: 'Expenses' }
    ],
    scrollPositionChanged: function(s, e) {
    	autoSizeVisibleRows(s, false);
    },
    loadedRows: function(s, e) {
    	setTimeout(function() {
      	autoSizeVisibleRows(s, false);
      }, 50);
    },
    resizedColumn: function (s, e) { // column resized
    	setTimeout(function() {
      	autoSizeVisibleRows(s, true);
      }, 50);
    },
    cellEditEnded: function(s, e) { // cell edited
    	if (s.columns[e.col].wordWrap) {
	    	autoSizeVisibleRows(s, true);
      }
		},
    rowEditEnded: function(s, e) { // whole row undo
    	if (e.cancel) {
	   		autoSizeVisibleRows(s, true);
	    }
		},
    itemsSource: data
  });
  
  // auto-size visible rows
  function autoSizeVisibleRows(flex, force) {
  	var rng = flex.viewRange;
    for (var r = rng.row; r <= rng.row2; r++) {
    	if (force || flex.rows[r].height == null) {
      	flex.autoSizeRows()
     ...