5.20203.748
5.20203.748

DataMaps in FlexGrid

In many situations, you may want columns to map values so cells display a value that is different from what is actually stored in the grid.

For example, you may have a 'rating' column with values ranging from zero to three, and you would like to display the strings 'Low', 'Medium', or 'High' instead.

Or maybe you have a 'customer' column that contains the customer ID, and you would like to display the customer name instead.

You could accomplish both tasks using the formatItem event, but the FlexGrid provides a better alternative: DataMaps. If you set a column's dataMap property to an instance of a DataMap, the grid will use it to:

  • Look up display values for each data item, and
  • Provide a drop-down list with valid items when editing the cells.

For example, the grid below has a 'Customer' column with a DataMap that associates customer names and IDs. The data source contains customer IDs, but the grid shows their names instead, and provides a drop-down list for selecting the customer for each item.

The grid also assigns a dataMap to the 'Country' column. In this case, the map is just a string array with the country names. There is no real mapping, but you still get the drop-down list to pick from. Users will not be able to enter any countries that are not on the list.

Example:

import * as wjGrid from '@grapecity/wijmo.grid';

// create some random data
var countries = 'US,Germany,UK,Japan,Sweden,Norway,Denmark'.split(',');
var customers = [
    { id: 0, name: 'Paul Perkins', address: '123 Main St' }, 
    { id: 1, name: 'Susan Smith', address: '456 Grand Ave' }, 
    { id: 2, name: 'Joan Jett', address: '789 Broad St' }, 
    { id: 3, name: 'Don Davis', address: '321 Shattuck Ave' }, 
];
var data = [];
for (var i = 0; i < countries.length; i++) {
    data.push({
        id: i,
        country: countries[i],
        customer: customers[i % customers.length].id,
        active: i % 5 != 0,
        downloads: Math.round(Math.random() * 200000),
        sales: Math.random() * 100000,
        expenses: Math.random() * 50000
    });
}

// create customer data map
var customerMap = new wjGrid.DataMap(customers, 'id', 'name');

// show the data in a grid
var theGrid = new wjGrid.FlexGrid('#theGrid', {
    showAlternatingRows: false,
    autoGenerateColumns: false,
    columns: [
        { binding: 'customer', header: 'Customer', width: '1.5*', dataMap: customerMap },
        { binding: 'country', header: 'Country', width: '*', dataMap: countries },
        { binding: 'downloads', header: 'Downloads', width: '*', format: 'n0' },
        { binding: 'sales', header: 'Sales', width: '*', format: 'n0' },
        { binding: 'expenses', header: 'Expenses', width: '*', format: 'n0' }
    ],
    itemsSource: data,
});