Skip to main content

Work with Grid

Working with columns and cells#

The API of dhtmlxGrid allows setting configuration of columns, getting an object of a particular column as well as the parameters of a certain cell.

Setting columns configuration#

You can specify the configuration of Grid columns on the fly via the setColumns() method. It takes an array with columns objects as a parameter.

grid.setColumns([    { id: "a", header: [{ text: "New header for column a" }] },    { id: "b", header: [{ text: "New header for column b" }] },    // more columns objects]);

You can find the full list of the available configuration options of a Grid column here.

Getting configuration of a column#

It is possible to return an object with attributes of a column via its id. Use the getColumn() method for this purpose.

var column = grid.getColumn("b"); // ->// {width: 100, id: "b", header: Array(1), $cellCss: {…}, type: "string"}

The method returns an object with configuration of the specified column. You can find the list of properties that the return object can contain here.

Getting configuration of a cell#

There is the getCellRect() method that returns an object with coordinates of a cell. The method takes as parameters the ids of the row and the column the cell belongs to:

var rect = grid.getCellRect("1","c");// -> {x: 200, y: -40, height: 40, width: 200}

The return object includes the following attributes:

x(number) the X coordinate of a cell
y(number) the Y coordinate of a cell
height(number) the height of a cell
width(number) the width of a cell

Getting header filter#

You may want to manipulate a filter specified in the header of a grid, for example, to set/unset the focus on the filter, to change the filter, or clear it. To do that, you should get an object of the header filter by column id via the getHeaderFilter() method:

var countryFilter = grid.getHeaderFilter("country");// -> returns HTMLElement// <label className="dhx_grid-filter__label dxi dxi-menu-down">...</label>
countryFilter.focus();
// or
var countryFilter = grid.getHeaderFilter("density");// -> returns Combobox// Combobox {_uid: "u1597304021754", config: {…}, events: EventSystem, // data: DataCollection, popup: Popup, …}
countryFilter.blur();

Related sample:Grid. Get Header Filter

The method returns either an HTML object or an object with Combobox configuration.

Hiding/showing a column#

It is possible to show and hide a column in the grid via the showColumn() and hideColumn() methods.

//showing a columngrid.showColumn(col);//hiding a columngrid.hideColumn(col);

Related sample: Grid. Show/Hide Column

Since the object of a column has the hidden property, the showColumn() method changes the value of the hidden property to false while the hideColumn() method changes the value of the property to true.

Checking visibility of a column#

You can check whether a column is hidden or shown on a page using the isColumnHidden() method. The method returns true, if a column is hidden, and false if it's visible.

grid.isColumnHidden("country"); // -> true|false

Related sample: Grid. Is Column Hidden

Hiding/showing a row#

Starting from v7.0, it is possible to show and hide a row in the grid via the showRow() and hideRow() methods.

//showing a rowgrid.showRow(rowId);//hiding a rowgrid.hideRow(rowId);

Related sample:Grid. Show/Hide Row

Checking visibility of a row#

You can check whether a row is hidden or shown on a page using the isRowHidden() method. The method returns true, if a row is hidden, and false if it's visible.

grid.isRowHidden("1"); // -> true|false

Related sample:Grid. Show/Hide Row

Adding/removing a row#

Adding a row#

You may add a new row into the grid by using the add() method of DataCollection:

grid.data.add({    "country": "Estonia",    "population": "1326535",    "yearlyChange": "0.0070",    "netChange": "3782",    "density": "31",    "area": "45339",    "migrants": "3911",    "fert": "1.59",    "age": "42.4",    "urban": "0.6790",    "id": "136"}, 0);

Removing a row#

To remove the necessary row from the grid, apply the remove() method of DataCollection. Pass the id of the row that should be removed to the method:

grid.data.remove("5");

Here is an example of removing a currently selected row:

const cell = grid.selection.getCell();grid.data.remove(cell.row.id);

Related sample: Grid. Delete Row

For more information about the selection functionality in Grid, read the Selection and Work with selection object articles.

Removing all rows#

If you need to remove all rows at once, use the removeAll() method of DataCollection:

grid.data.removeAll();

Adding/removing spans#

You can manipulate columns and rows spans inside the grid with the help of corresponding API methods: addSpan(), removeSpan() and getSpan().

Adding spans#

In order to add a col/row span into the grid, use the addSpan() method. Pass an object with configuration of a span as a parameter:

grid.addSpan({     row: "0",     column: "a",     rowspan: 5 });// grid.paint();

These are possible fields of a span object:

row(string|number) mandatory, the id of a row
column(string|number) mandatory, the id of a column
rowspan(number) optional, the number of rows in a span
colspan(number) optional, the number of columns in a span
text(string|number) optional, the text in a spanned row/column
css(string) optional, the name of the CSS class that will be applied to a span

Getting spans#

You can return the col/row span a cell is a part of using the getSpan() method. It takes the ids of the row and the column the cell belongs to as parameters:

var span = grid.getSpan("10","a"); // -> {row:"10", column:"a", colspan:4, text:"Some header", css:"myCustomColspan"}

As a result, you'll get an object with a span configuration, if any span includes the specified cell. Attributes of a span object are described above.

Removing spans#

To remove an existing span, make use of the removeSpan() method. It takes the ids of the row and the column as parameters:

grid.removeSpan("10","a");

Controlling scroll behavior#

The API of dhtmlxGrid provides the possibility to set scrolls to the necessary position and to get the current state of scrolls.

Scrolling to specific coordinates#

You can scroll grid content to exact position defined by x and y coordinates via the scroll() method. Pass the coordinates as parameters of the method.

grid.scroll(75,230);

Scrolling to specific grid cell#

It is also possible to scroll grid content to a particular cell. Pass the ids of the row and the column as parameters:

grid.scrollTo("15","c");

Related sample: Grid. Controlling Scroll Behavior

Getting the state of scroll#

To return the current state of scroll, use the getScrollState() method.

var state = grid.getScrollState(); // -> {x:0,y:0}

It returns an object with x,y coordinates of a position the grid has been scrolled to.

Filtering data#

You can filter grid data by the specified criteria with the help of the filter() method of DataCollection. The method takes as a parameter an object with the properties described below:

rule(object|function) the filtering criteria. It can be:
  • a filtering function. It takes as a parameter a data item (e.g. a row) and returns an object with a filtering rule.
  • or:
  • an object with the following attributes:
    - by - (string) mandatory, the id of a column
    - match - (string) mandatory, a pattern to match
    - compare - (function) a function for extended filtering that takes three parameters:
      - value - the value to compare (e.g. a column in a row)
      - match - a pattern to match
      - item - a data item the values of which should be compared (e.g. a row)
config(object) optional, an object with two properties:
  • add (boolean) defines whether each next filtering will be applied to the already filtered data (true), or to the initial data (false, default)
  • smartFilter (boolean) defines whether a filtering rule will be applied after adding and editing items of the collection

grid.data.filter(function (item) {  return item.a > 0 && item.b !== "Apple";});
grid.data.filter(function (item) {  return item.a > 0 && item.b !== "Apple";}, {  add: true});
grid.data.filter({  by: "a",  match: "Orange",  compare: function (value, match, item) {    if (item.a !== "Some") {      return val === "New";    }    return false;  }}, {  add: true,  smartFilter: true});

Related sample: Grid. Basic Filter

Sorting data#

It is possible to sort data in the grid via the sort() method of DataCollection. The method takes two parameters:

rule(object) an object with parameters for sorting. It can take the following attributes:
  • by (string) the id of a column
  • dir (string) the direction of sorting "asc" or "desc"
  • as (function) a function that specifies the type to sort data as
  • rule (function) optional, a sorting rule; the function must have two parameters and return a number (-1,0,1)
config(object) defines the parameter of sorting. It takes one attribute:
  • smartSorting (boolean) specifies whether a sorting rule should be applied each time after changing the data set

grid.data.sort({    by:"a",    dir:"desc",    as: function(item){        return item.toUpperCase();     },    {        smartSorting: true    }});

Related sample: Grid. Sorting Data

To discard all applied sorting rules, call the method without parameters:

grid.data.sort();

Custom sorting#

You can also specify the rule attribute in a passed object instead of the default ones and set a custom function for sorting. For example:

grid.data.sort({    rule: (a, b) => a.id > b.id ? 1 : (a.id < b.id ? -1 : 0) });

Getting the sorting state#

To get the current state of sorting data in Grid, use the getSortingState() method. The method returns an object with two attributes:

dir(string) the sorting direction (desc, asc)
by(string) the id of a column that the grid is sorted by

var state = grid.getSortingState(); // -> {dir: "desc", by: "country"}

Related sample: Grid. Get Sorting State

Editing data#

You can easily edit the desired cell of a grid with the help of the editCell() method. It takes two parameters:

row(string, number) the id of a row
col(string, number) the id of a column

For example, you can edit the first cell of the "project" column like this:

grid.editCell(grid.data.getId(0),"project");

Related sample: Grid. Editing Data

To finish editing of a cell, use the editEnd() method. The method takes a boolean value as a parameter to define whether the edited data will be saved after the editing of a cell is complete (if true, the made changes won't be saved).

grid.editEnd(); // the edited data will be saved
grid.editEnd(true); // the edited data won't be saved
note

The editEnd() method does not work if the type of the column editor is defined as checkbox.

Exporting Grid#

You can easily export data of Grid into the Excel or CSV format.

Exporting data to Excel#

dhtmlxGrid provides the possibility to export data from Grid into an Excel file by calling the xlsx() method of the Export module. The method takes an object with export settings as a parameter.

grid.export.xlsx({    name:"grid_data",    url: "//export.dhtmlx.com/excel"});

Export settings include:

url(string) the link to the server side where export will be processed.
By default, it is "//export.dhtmlx.com/excel"
name(string) the name of a ready Excel file

Related sample: Grid. Export

Exporting data to CSV#

You can export data from Grid to the CSV format with the csv() method of the Export module. The method takes an object with export settings as a parameter:

asFile(boolean) defines whether Grid should be exported to a file, true by default. To export Grid only as a CSV string, you need to set asFile:false.
name(string) the name of the exported CSV file (if asFile is not set to false).
rowDelimiter(string) a newline ("\n") by default. A separator between rows, can be a tab - "\t", or any other value.
columnDelimiter(string) a comma (",") by default. A separator between columns, can be a semicolon - ";", or any other value.

grid.export.csv({    name:"grid_data", // grid data will be exported to a CSV file named "grid_data"    rowDelimiter: "\t", // the tab delimiter will be used to separate rows    columnDelimiter: ";" // the semicolon delimiter will be used to separate columns});

Related sample: Grid. Export

The csv() method returns a CSV string with Grid data.

Repainting Grid#

In case you've changed some configuration settings of a grid, you can repaint it on a page via the paint() method:

grid.paint();

Destructing Grid#

When it's necessary to release resources occupied by Grid during its activity, you can make use of the destructor() method:

grid.destructor();

Using Selection API#

For information on using Selection API, read Work with Selection Object.