Check documentation for the latest version of dhtmlxSuite Common Operations with Grid and its Elements DHTMLX Docs

Common Operations with Grid and its Elements

In this article we'll compactly list basic operations that you will often use while developing apps with dhtmlxGrid.

Learn how to:
Grid
Row
Column
Cell


Grid

To attach a header row to the grid, use the attachHeader method:

Attaching the header to the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales"); mygrid.init();

Related sample:  Initialize object on page

Read more in article Headers and Footers.


To detach the header row, use the detachHeader method:

Detaching a header from the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales"); mygrid.attachHeader("#text_filter,#text_filter,#numeric_filter");
mygrid.init();
mygrid.detachHeader(0); //detaches the 1st header row

Read more in article Headers and Footers.

To attach a footer row to the grid, use the attachFooter method:

Attaching the footer to the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.attachFooter('Total sales,#cspan,${#stat_total}');

Related sample:  Numeric filtering and master checkbox

Read more in article Headers and Footers.


To detach a footer row, use the detachFooter method:

Detaching the footer from the grid

mygrid.attachFooter('Total sales,#cspan,${#stat_total}');   mygrid.attachFooter('Max sales,#cspan,{#stat_max}'); 
mygrid.attachFooter('Min sales,#cspan,{#stat_min}');
mygrid.detachFooter(0); //detaches the 1st footer row

Read more in article Headers and Footers.

Clearing the grid

To clear the grid from the data, use the clearAll method :

Reloading the grid's data

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.load('data.xml',function(){
    mygrid.clearAll();                      //removes all rows });

Related sample:  Refresh grid from XML


To delete all rows from the grid and clear the header therewith, use the clearAll method with the true parameter:

Reloading both the grid's structure and data

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setImagePath("../codebase/imgs/");
mygrid.load("gridH.xml",function(){
    mygrid.clearAll(true); //removes all rows and clears the header  });

Related sample:  Reload with new structure

Destructing the grid

To destruct the grid and clear the occupied memory, use the destructor method:

Using the grid's destructor

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.destructor();

Related sample:  Decrease memory usage

Reloading the grid

To reload the grid (clear all rows and reload data), use the clearAndLoad method:

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.clearAndLoad("data/grid.xml");

Related sample:  50,000 records in grid with paging


An alternative way to reload the grid is to use a couple of methods - clearAll and load:

Reloading the grid's data

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.load('data.xml',function(){
    mygrid.clearAll(); //removes all rows     mygrid.load("data1.xml");                               });
 
 
//or (to reload both grid's data and header)
mygrid.clearAll(true); //removes all rows and clears the header  mygrid.load("gridH_new.xml");

Related sample:  Refresh grid from XML

Related sample:  Reload with new structure

Skinning the grid

To set one of predefined skins for the grid, use the setSkin method:

Setting the skin for the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue"); mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();

Related sample:  Initialize object on page

Row

Adding/removing a row

To add a new row to the grid, use the addRow method:

Adding a new row to the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.addRow(mygrid.uid(),"The Rainmaker,John Grisham,7.99");

Related sample:  Add/Delete Rows in Grid


To delete a row in the grid, use the deleteRow or deleteSelectedRows method:

Deleting a row from the grid

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.deleteRow("row123");   //deletes the row with id="row123"  //or 
mygrid.deleteSelectedRows();  //deletes all selected rows from the grid

Related sample:  Add/Delete Rows in Grid

Getting the row id/index

To get the ID of a row, use the getRowId method:

Getting the id of a row

var rId = mygrid.getRowId(1); //returns the id of the 2nd row mygrid.deleteRow(rId);

Related sample:  Add/Delete Rows in Grid


To get the index of a row, use the getRowIndex method:

Getting the index of a row

var selectedRow = mygrid.getSelectedId();
var rIndex = mygrid.getRowIndex(selectedRow); //gets the index of the selected row

Related sample:  Auto height

Checking row existance

To check whether a row with the specified id exists, use the doesRowExist method:

Checking whether a specific row exists

var isExist = mygrid.doesRowExist("row5"); //returns true,if a row with id='row5' exists

Getting the number of rows

To get the number of rows in the grid, use the getRowsNum method:

Getting the number of rows in the grid

var count = mygrid.getRowsNum(); function sumColumn(ind){
    var out = 0;
    for(var i=0;i<count;i++){         out+= parseFloat(mygrid.cellByIndex(i,ind).getValue())
    }
    return out;
}

Related sample:  Using Grid API Methods

Setting the row ID

To set a new ID for a row with the specified index, use the setRowId method:

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");
mygrid.setHeader("Book Title,Author,Sales");
mygrid.init();
mygrid.load("data.xml", function(){     mygrid.setRowId(0,"new_id") });

Related sample:  Using Grid API Methods

To set a new ID for a row with the specified ID, use the changeRowId method:

mygrid.changeRowId("old_id","new_id");

Selecting a row

To select a row with the specified index, use the selectRow method:

mygrid.selectRow(0); //selects the 1st row in the grid

Related sample:  Using Grid API Methods

To select a row with the specified ID, use the selectRowById method:

mygrid.selectRowById("row5");            //selects the row with the id='row5'

To select all rows in the grid, call selectAll method:

mygrid.selectAll();

Hiding a row

To hide a row with the specified ID, call the setRowHidden method:

mygrid.setRowHidden("row5",true);        //hides the row with the id='row5'

To show the row after this, call the same method but with the false parameter:

mygrid.setRowHidden("row5",false);       //shows the hidden row with the id='row5'

Related sample:  Complex content in header

Programmatic scrolling the grid for making the specified row visible

To programmatically scroll the grid to make a row with the specified ID visible, call the showRow method:

mygrid.showRow("row5");      //scrolls the grid to show the row with the id='row5'

Making the grid multi-line

To enable the possibility to have multi-line rows in the grid, call the enableMultiline method:

mygrid.enableMultiline(true);            //enables the multi-line mode in the grid

Related sample:  Multiline cells

Column

Adding/removing a column

To add a new column to the grid, call the insertColumn method:

mygrid.insertColumn(0);            //inserts a column in the 1st position

To remove a column, call the deleteColumn method:

mygrid.deleteColumn(0);            //deletes the 1st column

Related sample:  Insert/Delete column

Adjusting the width of a column to the content

To adjust the width of a column to the content, call the adjustColumnSize method:

mygrid.adjustColumnSize(0);      //adjusts the width of the 1st column to the content

Related sample:  Adjust column size

Checking visibility of a column

To check whether a column is visible or hidden, call the isColumnHidden method:

mygrid.isColumnHidden(0);        //returns 'true' if the 1st column is hidden

Related sample:  Hide/Show column

Getting the column Id/Index

To get the ID of a column, call the getColumnId method:

var cId = mygrid.getColumnId(1);             //gets the id of the 2nd column

To get the index of a column, call the getColIndexById method:

var cIndex = mygrid.getColIndexById("col3"); //gets index of the column with id='col3'

Related sample:  Using Grid API Methods

Getting the number of columns

To get count of columns in the grid, call the getColumnsNum method:

var count = mygrid.getColumnsNum();

Related sample:  Using Grid API Methods

Getting/setting the sorting parameters of a column

To get the index of a column the grid is currently sorted by and the sorting order, call the getSortingState method:

var state = mygrid.getSortingState(); 
//returns [0,"des"] if the grid is sorted by the first column in descending order

To set the sorting type for the grid columns, call the setColSorting method:

mygrid.setColSorting("int,str,date,na,sortingFunction");

Getting/setting the type of a column

To get the content type of a column with the specified index, call the getColType method:

var type = mygrid.getColType(0);   //returns the type of the 1st column

To get the content type of a column with the specified ID, call the getColTypeById method:

var type = mygrid.getColTypeById("col3"); //returns type of the column with id='col3'

To set the content types for the grid columns, call the setColTypes method:

mygrid.setColTypes("dyn,ed,txt,price,ch,coro,ra,ro");

Getting/setting the width of a column

To get the width of a column, call the getColWidth method:

var type = mygrid.getColWidth(0);   //returns the width of the 1st column

To set the width for a column, call the setColWidth method:

mygrid.setColWidth(0,"150");   // sets the width of the 1st column to 150px

To set the width for all columns of the grid, call the setInitWidths method:

mygrid.setInitWidths("150,100,100,100,100");

You can use the * (asterisk) as the width value to force a specific column to fill up the remaining width. If you use * for several columns they will share out the remaining width equally.

//2 last columns equally divide the remaining width between themselves 
mygrid.setInitWidths("150,100,100,*,*");

Hiding a column

To hide a column with the specified ID, call the setColumnHidden method:

mygrid.setColumnHidden(0,true);        //hides the 1st column

To show the column after this, call the same method but with the false parameter:

mygrid.setColumnHidden(0,false);       //shows the 1st column hidden before

Set the column horizontal alignment

To set the horizontal alignment for the grid columns, call the setColAlign method:

mygrid.setColAlign("right,left,center,justify");

Cell

Getting/setting the cell object

To get the object of a cell with the specified row id and column index, call the cellById method:

var cellObj = grid.cellById("row5",0); // gets object of 1st cell in row with id='row5'

To get the object of a cell with the specified row and column indices, call the cellByIndex method:

var cellObj = grid.cellByIndex(0,0); // gets the object of the 1st cell in the 1st row

Selecting a cell

To select a cell, call the selectCell method:

mygrid.selectCell(0,1);    //selects the second cell of the first row

Merging Cells

To activate the possibility of merging cells in the grid, the user can display row cells in the same way as he uses colspan or rowspan in an HTML table. Cell groups can be managed from XML or Script. In both cases rowspan and colspan must be enabled during the dhtmlxGrid initialization:

grid.enableRowspan();
grid.enableColSpan(true);

The user should include dhtmlxgrid_rowspan.js file into the page to make rowspan work. Colspan doesn't require any additional files. There are several methods responsible for grouping and ungrouping cells with colspan and rowspan.

Managing cell groups from XML

The number of cell tags in a row should not be changed. The example of a row with 3 cells, 2 of which are grouped, is presented below:

<row id="r01"> 
    <cell colspan="2">value</cell> 
    <cell/> 
    <cell>value of third cell</cell> 
</row>

The same for rowspan:

<row id="r01"> 
    <cell rowspan="2">value0</cell> 
    <cell>value1</cell> 
</row> 
<row id="r02"> 
    <cell/> 
    <cell>value2</cell> 
</row>

Managing cell groups from script

1) Setting colspan in a row starting from the specified column's index:

grid.setColspan(row_id, col_ind, colspan);

The parameters of this method are the following:

  • row_id - id of the row;
  • col_ind - index of the column;
  • colspan - size of the colspan (the number of cells in a group).

2) Setting rowspan with a specified length starting from the specified cell:

grid.setRowspan(rowID,colInd,length);

The parameters of this method are the following:

  • rowID - id of the row;
  • colInd - index of the first cell in the group;
  • length - length of the rowspan (number of cells in the roup).

For example:

// group two cells with colspan
grid.setColspan("r01",0,2);
// ungroup cells
grid.setColspan("r01",0,1);
// group two cells with rowspan
grid.setRowspan("r01",0,2);
// ungroup cells
grid.setRowspan("r01",0,1);

Simultaneous usage of rowspan and colspan for one cell is impossible. Also note that setColspan() and setRowspan() methods must be called only after proper rows are loaded.

Manipulating text of a cell

The user can set text style for a specified cell in the following way:

grid.setCellTextStyle(row_id, ind, styleString);

The parameters are the following:

  • row_id - id of the row;
  • ind - index of the cell;
  • styleString - style string in the common format (example: “color:red;border:1px solid gray;”).

Editing cells

The following method creates the Editor object and switches the currently selected cell to the edit mode if it is allowed:

grid.editCell();

The following method should be used to return the value from the editor (if it is present) to the cell and close the editor:

grid.editStop(mode);

Manipulating Marked Cells

There is a possibility to set marked cells support for enabled or disabled state in dhtmlxGrid. The user should include dhtmlxgrid_markers.js file into the page to work with this functionality.

grid.enableMarkedCells(state); // true/false

A cell can be marked/unmarked (selected or deselected) from script in the following way:

grid.mark(r,cInd,state);

The parameters are the following:

  • r - row object or index of the row;
  • cInd - index of the cell;
  • state(true/false) - select or deselect the cell in question.

The user can get marked cells in the following way:

grid.getMarked();

The method returns the array of marked cells (pairs of row id and column index). To unmark all cells in the grid, the user should call the following command:

grid.unmarkAll();

Enabling unique ids for cells

There is a method that is capable of enabling/disabling unique ids for cells. Ids will be automatically created using the following template: “c_[RowId]_[colIndex]”.

grid.enableCellIds(mode); // true to enable, false to disable

Finding a cell

To find a cell in the grid by its value, the user should apply the following method:

var cell = grid.findCell(value, c_ind, first);

The user shouldn't forget to include dhtmlxgrid_filter.js file into his project. The parameters of the above-mentioned method are:

  • value - search string;
  • c_ind - index of the column to search in (optional; if it is not specified, search will be held through all grid);
  • first - finds only the first occurrence (optional parameter).

The method returns an array, each member of which contains an array with row id and cell index.

Back to top