guide
dhtmlXGrid Guide and Samples
Main features
New in version 1.5
Supported browsers
Working with dhtmlXGrid
Navigation with keyboard
Initialize object on page
Specify additional parameters of the grid:
Set Event Handlers
Event names available here. In most cases functions specified inside event handlers get some values with the arguments. For details about passed arguments please refer to Events documentation. Inside event handlers set with attachEvent, you can refer to grid object through this
Adding nodes with Script
Loading data with XML
In PHP script use the following code for page header:
\n"); ?>
<rows> node is mandatory. It can contain grid related <userdata> blocks and rows (<row>)
Attributes:
<row> can contain row related <userdata> blocks and cells (<cell>).
Attributes:
<cell> contain cell value. Can contain html (use CDATA block if you include htmlx tags) or XML (since v.1.2)
Attributes:
To set userdata directly within XML use <userdata>
It has just one parameter:
and value to specify userdata value
Adding nodes with Script
Serializing Grid
setSerializationLevel arguments:
Serialization to CSV possible since v.1.2 (Professional Edition only)
Dynamical Loading while scrolling
See chapter "Loading data with XML" for xml structure and syntax of methods
Buffering
Manipulating rows
Moving Rows
Context Menu in Grid
For HTTPS compatibility we added two more parameters to context menu constructor:
TreeGrid XML structure
Smart XML Parsing
Checkboxes & Radiobuttons
Increasing Performance
Taking into account the general low performance of DHTML we introducrd two ways of increasing performance of large grids:
1. Dynamical Loading2. Buffering
3. Distributed Parsing
4. Smart Rendering for rows (preferable for big grids)
5. Paging
6. "FAST" mode
Distributed Parsing
Multiline grid rows
Multiselection in Grid
Drag-n-drop in Grid
There are two modes of drag-n-drop in TreeGrid. You can manage it with setDragBehavior method passing following values as method parameter:
Modes can be switched on/off any time.
Extended Drag-n-drop mode
Copy with drag-n-drop
Use "mercy drag" to copy records from one grid to another or within same grid with drag-n-drop:Math Formulas in Grid
Math formulas with Script: You can attach necessary math formula to column while defining its type with setColTypes. Use [=...] to set formula to the nesessary column. At the same time you still use any of available eXcells to format the result: mygrid.setColTypes("ed,ed,ed,ed,ed[=c2*c3]"); In the example above c2*c3 means that the value of last column should be equel to the product of column 2 value and column 3 value. Column indexes are zero-based. You may use any javascript math operators as long as you refer to correct columns (existing columns with numeric values).
Rounding resulting values. Togather with Math formulas you may need to use the following grid method to round resulting values: mygrid.setMathRound(decimal_places); decimal_places - number of digits after point.
Editing formulas in grid.
By default all cells with formulas are read-only, thus user can't change the formula on the fly. But you still can enable formula editing using the following method: mygrid.enableMathEditing(state); state - false(by default) means that all formula cells are read-only, true - editable.
Math formulas with XML: ... =c2*c3 To set formula for single cell you can define it directly in xml as cell value, starting expression with "=". Column type should still be defined with Math formula (see above) or as type "math".
Math Formulas in TreeGrid
Light Mouse Navigation
Configuration via XML
Important: do not call grid.init() when you configure grid from xml. mygrid = new dhtmlXGridObject('gridbox'); mygrid.setImagePath("../codebase/imgs/"); mygrid.loadXML("gridH.xml");//xml which contains configuration block togather with data
All necessary settings, like columns types and dimentions can be set within xml inside <head> tag:
Since v.1.2 you also can specify grid methods to run before or after grid initialization.
string value string value Sales Shipping 1 Day 1 Week ... ... % ... ... Text value of <column> tag will be used as a label for column
Possible attributes for column tag are:
Settings inside settings tag:
Specifying combobox and selectbox values:
To specify values for co and coro columns add <option> tag(s) inside relative <column> tag.
Running grid methods from XML
xp 1true ... Same as with script: mygrid = new dhtmlXGridObject('gridbox2'); ... mygrid.setSkin("xp"); mygrid.init(); mygrid.setColumnHidden(1,true);
Interaction with dhtmlxTree (drag-and-drop between components)
The complexity of drag-n-drop between tree and grid conditioned by different structure of data in them. So you need to define what values in grid should go to tree node and how to store them there and vice versa.
There are two methods in grid for this:
All you need is to redefine them the way you need. Example: //redefine tree-to-grid drop element mygrid.treeToGridElement = function(treeObj,treeNodeId,gridRowId){ this.cells(gridRowId,1).setValue(treeObj.getItemText(treeNodeId)); if(treeObj.getUserData(treeNodeId,"c0")){ this.cells(gridRowId,0).setValue(treeObj.getUserData(treeNodeId,"c0")); this.cells(gridRowId,1).setValue(treeObj.getUserData(treeNodeId,"c1")); this.cells(gridRowId,2).setValue(treeObj.getUserData(treeNodeId,"c2")); this.cells(gridRowId,3).setValue(treeObj.getUserData(treeNodeId,"c3")); } return !document.getElementById("dnd_copy").checked; } //redefine grid-to-tree drop element mygrid.gridToTreeElement = function(treeObj,treeNodeId,gridRowId){ treeObj.setItemText(treeNodeId,this.cells(gridRowId,1).getValue()+"/"+this.cells(gridRowId,2).getValue()) treeObj.setUserData(treeNodeId,"c0",this.cells(gridRowId,0).getValue()) treeObj.setUserData(treeNodeId,"c1",this.cells(gridRowId,1).getValue()) treeObj.setUserData(treeNodeId,"c2",this.cells(gridRowId,2).getValue()) treeObj.setUserData(treeNodeId,"c3",this.cells(gridRowId,3).getValue()) return !document.getElementById("dnd_copy").checked; }
Usage of Cell Editors (eXcell)
Special types:
To assign necessary types to columns use the following script method with comma delimmited list of editor codes: mygrid.setColTypes("ro,ed,txt,txt,ro,co");
Since v.1.2 you also can set type of each cell, row or change default column type:
Script syntax:
mygrid.setRowExcellType(rowId,type);//sets all cells in row to specified type mygrid.setCellExcellType(rowId,cellIndex,type);//sets particular cell type mygrid.setColumnExcellType(colIndex,type);//changes column typeXML syntax:
...Data Processing and link with Server Datasource

Main Features:
- cell after cell editing was finished it checks if all mandatory cells in row got their values and these values passed the validation and if yes, then sends data to server
- row same as point 1, but it occurs when row selection was changed or Enter button pressed.
- off no automatic data sending, all updated/deleted data is sent to server on calling script method (you can assign it to button, so user can choose when to save)
Unified Server-side routine:
There is unified server side routine for single table grids written in PHP 5. You need only configure XML file according to your data structure all Select, Insert, Update, Delete actions will be done automaticaly.
Client Side Code Sample:
... mygrid.init(); //============================================================================================ //To use our automated methods you should always point your grid to same file - member of dhtmlxGridDataProcessor library (just check the path) mygrid.loadXML("dataLink/get.php"); //init dataprocessor and assign verification function //specify server update processor - member of dhtmlxGridDataProcessor library (just check the path) or your own myDataProcessor = new dataProcessor("dataLink/update.php"); //verify if the value of 2nd column (zero-based numbering is 1) is not empty myDataProcessor.setVerificator(1) //verify value of 4th column (zero-based numbering is 3) against checkIfNotZero verification function (see it below) myDataProcessor.setVerificator(3,checkIfNotZero) //you can also specify update mode. Availabel modes are: update automaticaly (cell based, row based) and manual update //cell ("cell") based mode means that grid will attempt to update data on server after each editing of cell (on editor closed). //row ("row") based mode means that grid will attempt to update data on server when row selection changed or Enter key pressed //manual ("off") means that you need to run myDataProcessor.sendData() to begin update process (automatic update off). myDataProcessor.setUpdateMode("off");//available values: cell (default), row, off //initialize data processor for the grid object (in our case - mygrid) myDataProcessor.init(mygrid); //============================================================================================ //Example of verification function. It verifies that value is not 0 (zero). //If verification failed it should return false otherwise true. //Verification fucntion specified in setVerificator method will always get two argumentrs: value to verify and column name (use it for message) function checkIfNotZero(value,colName){ if(value.toString()._dhx_trim()=="0"){ showMessage(colName+ " should not be 0") return false }else return true; }Re\Definition of actions
There are built-in actions in dhtmlxDataProcessor which are used during data processing:You can define your own handlers for each of them by myDataProcessor.defineAction("update",myHandler); in such case the myHandler will be called after update operations, returning true from custom handler will allow default update actions.
You can define any other action youselves. All you need is to use following syntax in xml returned by server side: anything and the following javascript code: myDataProcessor.defineAction("[action name]",myHandler); myHandler function will be called and get <action> tag object as incoming argument.
Server side Unified routine usage
- cXX - grid columns [XX - is zero based column index]
- gr_id - grid row ID
- userdata blocks will use their names
- !nativeeditor_status - exists and value is "inserted" for insert operation, value is "deleted" for delete, doesn't exist or value is "updated" for update operation
If you do not use our built-in Unified routine and use your own file for processing data sent by dataProcessor you need to know the following:
- gr_id - row ID
- cXX - grid columns [XX - is zero based column index], like c1, c15 (to use column IDs instead of indexes you need to call enableDataNames(true) method of dataprocessor object. In this case parameter names will be created from IDs without any prefix)
- userdata blocks passed with their names
Data Processing and Server errors handling
Returning false from myHandler will prevent default event processing.
Tree-&-Grid initialization and usage
Necessary JS file:
Additional js file needed is dhtmlxtreegrid.js
Script initialization
Script initialization is the same as for grid. All you need is to decide what column should have tree structure and use "tree" eXcell for it.
XML structure as follows: userdata value 1 userdata value for honda Honda ... ...
All xml tags and attributes same as for dhtmlxGrid plus:
<rows> element can have the following attribute with treeGrid:
<row> treeGrid specific attribute:
<cell> element treeGrid specific parameter is:
Define new Cell Editors (eXcell)
Complete way (not necessary to follow - just for understanding. Important if you want to incorporate some external editor f.e.)
1. Choose the code for the new eXcell. In our case it is "test".
2. Get eXcell template: function eXcell_test(cell){ try{ this.cell = cell; this.grid = this.cell.parentNode.grid; }catch(er){} /** * @desc: method called by grid to start editing */ this.edit = function(){ } /** * @desc: get real value of the cell */ this.getValue = function(){ return ""; } /** * @desc: set formated value to the cell */ this.setValue = function(val){ if(val.toString()=="") val = " "; this.cell.innerHTML = val; } /** * @desc: this method called by grid to close editor */ this.detach = function(){ this.setValue(this.obj.value); return this.val!=this.getValue(); } } eXcell_test.prototype = new eXcell; 3. Add necessary code to this.edit() method. In particular it is creation of textfield inside grid cell and put there real (not formatted) value of the cell using this.getValue() method. this.edit = function(){ this.val = this.getValue(); this.obj = document.createElement("TEXTAREA"); this.obj.style.width = "100%"; this.obj.style.height = (this.cell.offsetHeight-4)+"px"; this.obj.style.border = "0px"; this.obj.style.margin = "0px"; this.obj.style.padding = "0px"; this.obj.style.overflow = "hidden"; this.obj.style.fontSize = "12px"; this.obj.style.fontFamily = "Arial"; this.obj.wrap = "soft"; this.obj.style.textAlign = this.cell.align; this.obj.onclick = function(e){(e||event).cancelBubble = true} this.obj.value = this.val this.cell.innerHTML = ""; this.cell.appendChild(this.obj); this.obj.focus() this.obj.focus() } 4. Now edit this.setValue(val) to format incomming value: this.setValue = function(val){ if(val.toString()=="") val = " "; if(isNaN(Number(val))){ this.cell.align = "left"; }else{ this.cell.align = "right"; } this.cell.innerHTML = val; } 5. Now we are ready to edit this.getValue(). As we haven't added any additional elements to the cell content - the will be just one line of code inside: this.getValue = function(val){ return this.cell.innerHTML.toString(); } 6. Final step is to get rid of editor and fill cell with formated value in this.detach() method: this.detach = function(){ this.setValue(this.obj.value); return this.val!=this.getValue(); } 7. You can get the complete code here. Make sure your place your eXcell code after dhtmlxgridcell.js.
Express way (make eXcell based on existing eXcell of common type)
You can base your eXcell on one of existing eXcell - the choice depends on how the value should be edited. For example simple text field is enough for your needs, but you need some special formating. The do the following: 1. C hoose the code for the new eXcell. In our case it is "test" again.
2. Template will be simplier and will be based on simple editor (code: ed). Some new code from the beginning, but then we skip this.edit() and this.detach() function eXcell_test(cell){ this.base = eXcell_ed; this.base(cell) this.getValue = function(){ return ""; } this.setValue = function(val){ } } eXcell_test.prototype = new eXcell_ed; 3. getValue and setValue you can get from points 4 and 5 above.
Usage of eXcell
Now you can use your new eXcell among other editors: mygrid.setColTypes("ed,ro,test"); Important: Starting from dhtmlxGrid 1.2 the new behaviour implemented - any click outside the grid causes editor closing. So if editor implemented as absolute positioned elements attached outside of grid it must catch and block onClick event, like this: div.onclick=function(e){ (e||event).cancelBubble=true; return false; }
Paginal Output
In sample below number of rows per page set to 30 and number of pages per group set to auto (null) - based on rows in first portion loaded from server
In case of using Autoloading, it delivers for example 100 more records each time previous 100 was consumed untill it reaches the end. As far as Grid knows nothing about the final number of records when uses autoloading, it shows actual number of rows already loaded from server in records info block, like "Records 200-230 from known 300".
If you do not use Autoloading or end of records was reached , Grid will know exact number of rows. Thus record info will be like this: "Results 200-230 from 300"
Script syntax
dhtmlxGrid API contains additional methods for managing paginal output with script.
Version/Edition: v1.1/Professional
Required js file:dhtmlxgrid_pgn.js
Smart Rendering
When this mode activated only those rows are rendered which are in visible area. You can use it with already loaded content or activate dynamical loading to fetch rows from server each time (or activate buffering additionaly to decrease number of server requests).
Important: if you activated dynamical loading you should understand that rows which are not loaded yet can't be used in script methods (select, delete etc.).
Script syntax:
Version/Edition: v1.1/Professional, v1.1/Standard for SR with dynamical loading
Required js file:dhtmlxgrid_srnd.js
Merging cells in grid
XML syntax:
Same for rowspan:
value0 value1 > <cell>value2<cell>Script syntax:
mygrid.setColspan("r01",0,2);//group two cells with colspan //r01 - row id //0 - first cell in group //2 - cells in group //-------------------------- mygrid.setColspan("r01",0,1);//ungroup cellsor for rowspan:
mygrid.setRowspan("r01",0,2);//group two cells with rowspan //r01 - row id //0 - first cell in group //2 - cells in group //-------------------------- mygrid.setColspan("r01",0,1);//ungroup cellsImportant: simultanious usage of rowspan and colspan for same cell is not possible
Version/Edition: v1.1/Professional
Split Mode. Frozen Columns
Important: we recommend using this mode with some performance optimization technologies (paginal output, smart rendering) taking into account complex script processing in split mode.
Important: this mode is incompatible with some grid functionlity.
Script syntax:
Grid: Version/Edition: v1.1/Professional
TreeGrid: Version/Edition: v1.1/Professional
Required js file:dhtmlxgrid_splt.js
Icons in Header
XML syntax:
Without Icon img:[path/to/icon.gif]With Icon ...Script syntax:
mygrid.setHeader("Without Icon,img:[path/to/icon.gif]With Icon");Version/Edition: v1.1/Standard
Dynamical Loading in treeGrid
- When initializing treeGrid, specify url of server routine which returns nested level mygrid.kidsXmlFile="pro_treeGrid_dynamic.php"; This routine will get url parameter id which is id of row, whcih was opened (in other words - id of row which is parent to the level which should be returned by mentioned routine)
- Initial treeGrid xml (as well as xml returned by routine mentioned in point 1) should have <row> tags with attribute child="1" (only rows which have children) ... ...
- XML returned by routine specified in point 1 should have attribute parent="xxx" in top level tag <rows> ... ...
Version/Edition: v1.0/Standard
Add/Delete/Move columns
Add\Delete\Move column with script
mygrid.insertColumn(index,label,typeCode,width) mygrid.deleteColumn(index); mygrid.moveColumn(oldInd,newInd);Move with drag-n-drop
mygrid.enableColumnMove(true); //to prohibit\alow moving some (or all) columns in some condition use event handler (moving allowed if it return true) mygrid.setOnBeforeColumnMove(function(sInd,tInd){ return confirm("Allow move column "+sInd+" to position "+tInd);//return true to allow, false - to prohibit });Version/Edition: v1.2/Professional
Required js file:dhtmlxgrid_mcol.js
Export to/from CSV
Version/Edition: v1.2/Professional
Required js file:dhtmlxgrid_nxml.js
Copy data to Excel (clipboard operations)
Selecting block of cells in Grid
Since v1.3. block selection is available in dhtmlxGrid. To enable it and use selection to copy data to clipboard you need to include following files:Color of selection can be chnaged in dhtmlxgrid.css in class definition for .dhtmlxGrid_selection; it is yellow by default;
To enable block selection do the following: mygrid.enableBlockSelection();
Copy block selection content to clipboard
If block is active you can copy its contnet to clipboard (if this allowed by the browser) mygrid.copyBlockToClipboard()Copy Grid data to clipboad with script
mygrid.gridToClipboard();//copy entire grid to clipboard in csv format mygrid.rowToClipboard();//copy selected rows to clipboard in csv format mygrid.cellToClipboard();//copy selected cell value to clipboard Important: this functionlity is prohibitted in FireFox by defaultImportant: to insert copied data to MS Excel you should set tab as delimiter (using setCSVDelimiter method)
Paste from clipboard to grid
//update entire grid from clipboard mygrid.clearAll();//clears grid mygrid.gridFromClipboard();//set grid content from clipboard (uses active delimiter) mygrid.updateRowFromClipboard();//updates selected row from clipboard (valid row content whould be in clipboard) mygrid.addRowFromClipboard();//adds rows from clipboard to grid mygrid.updateCellFromClipboard(); //sets clipboard content as selected cell valueVersion/Edition: v1.2/Professional
Required js file:dhtmlxgrid_nxml.js
Setting cell type explicetly
XML Syntax
Simple text editor Multiline Text Editor Default (as was set for column) eXcell type ...Setting cell type with script
mygrid.setRowExcellType(rowId,type);//sets all cells in row to specified type mygrid.setCellExcellType(rowId,cellIndex,type);//sets particular cell type mygrid.setColumnExcellType(colIndex,type);//changes column typeVersion/Edition: v1.2/Professional
Multiline Headers\Footer
Adding header Rows with script
//add second row to header mygrid.attachHeader("#rspan,Title,Author,#rspan,#rspan,#rspan,Bestseller,Published"); mygrid.setSizes();//call this method if row was added after grid initialization //#rspan - include cell in rowspan //#cspan - include cell in colspanAdding header Rows with XML (using call tag)
... #rspan,Title,Author,#rspan,#rspan,#rspan,Bestseller,Published ...Adding Footer to grid
mygrid.attachFooter("Label 1,#cspan,Label 3");//pass list of necessary labels mygrid.attachFooter("Label 1.1,Label 1.2,#rspan");//this will add second row to footer //#cspan - include cell in colspan //#rspan - include cell in rowspanSetting style to footer
To modify default style of footer - redefine "div.gridbox div.ftr td" after dhtmlxgrid.css was placed on page /*this will set default footer text align to right*/ div.gridbox div.ftr td{ text-align:right; }To set explicit style for each cell in footer use second argument of attachFooter method. //will set color of 1st and 2nd cells and align to 1st cell mygrid.attachFooter("Label 1,Label 2,Label 3",["color:red;textalign-left","color:blue"]);
Set dynamic content in footer
//add containers to footer cells where you need to set content dynamically mygrid.attachFooter("Total quantity,#cspan,-,Version/Edition: v1.2/Professional
Save\Restore column width
Saving\restoring columns width with script methods
mygrid.saveSizeToCookie();//to save column width mygrid.loadSizeFromCookie();//to load width from cookiesAutomatically save\restore column width
mygrid2.enableAutoSizeSaving();//enable automatic saving width mygrid2.loadXML("gridH.xml",function(){ mygrid2.loadSizeFromCookie();//restore width when grid loaded });Version/Edition: v1.2/Professional
Required js file:dhtmlxgrid_ssc.js
Initialize Grid from HTML table
Automatic initialization
| Column 1 | Column 2 |
| value 11 | value 12 |
| value 21 | value 22 |
Initialize from any table with script command
//param 1 - id of table to convert to grid var mygrid = new dhtmlXGridFromTable('tblToGrid');Possible grid related table/tr/td properties:
TABLE:TR:
TD (of first row):
TD (any row):
Version/Edition: v1.2/Professional/Standard
Required js file:dhtmlxgrid_start.js
Smart Parsing in dhtmlxTreeGrid
Current sample demonstrates loading of 1700 nodes on 4 levels. No need to change anything on server side.
Script Syntax
mygrid.enableSmartXMLParsing(true);Version/Edition: v1.2/Professional
Skins
Available skins are:
yourGrid.setSkin("modern");
Creation of Filter for Grid
Filtering by many values at once
Adding Filters into Grid Header
- greater than (like: ">100"),
- less than (like: "<100"),
- equel to (like "=100" or "100"),
- range (like "10..100")
So, how to add filters to your grid. It is simple. Add new row to grid header and use filter name with prefix (#) as cell content. Like this:
//set first row of header grid.setHeader("Book Title,Author,Price"); //set second row of header and define filters in it grid.attachHeader("#text_filter,#combo_filter,#numeric_filter");Grouping by value
Also records can be ungrouped. It is also possible to expand/collapse groups programatically. After changing data in the column grid was grouped by, it will automatically rearrange rows to fit the group.
To group data use the following command:
mygrid.groupBy(COLUMN_INDEX) where COLUMN_INDEX is the index of the column you want data be grouped by.Calling same command for another column index will regroup data.
To return grid into plain view call the following command:
mygrid.unGroup();Other grouping related methods are: expandGroup, collapseGroup, expandAllGroups, colapseAllGroups.
Extending Grid Usability
Manage columns in grid with popup menu
Starting from v.1.5 you can enable popup menu for Grid where user can set visibility for different columns right on the fly. To do this just include /codebase/ext/dhtmlxgrid_hmenu.js on the page with grid and call the following command:
mygrid.enableSomething();Using different keymaps in Grid
Starting from v.1.5 you can choose between default and 2 predefined (MS Excel like, MS Access like) keymaps. To switch to not defaukt keymap include necessary js file into the page with grid (will effect all grids on the page):
Define Tab order in grid
Starting from v.1.5 tab order in grid can be changed using setTabOrder method with comma delimited list of tab indexes for each column.
Lines between nodes
You can enable/disable lines between treegrid nodes (disabled by default) including codebase/ext/dhtmlxtreegrid_lines.js into the page and calling the following command:
treegrid.enableTreeLines(true);Adding Subrows and Nested Grids
There is a possibility to define cell as subrow or subgrid. In this case cell content will be moved to the expandable row below the current one.
Subrows
In case of subrow you can either set static content or load it while user expands subrow for the first time (in this case you need to specify url where to get content). To set cell as subrow use one of the following celltypes:
Subgrid
Using this technique you can incude independednt grid of any structure into current grid. To create it you need to use cell type:
Split mode limitation: subrow or subgid cell can be used in right part of grid with activated split mode.
Pivot table
Starting from v.1.5 you can use dhtmlxGrid as a base for PIVOT table.
To activate PIVOT use makePivot method. Argements are as follows:
Available properties of PIVOT parameters object are:
Automatically calculated values for header/footer
Starting from v.1.5 it became easy to add automatically calculated values to grid footer or header. There is a list of available types:
To activate this functionality you need to include dhtmlxgrid_filter.js into the page and use names listed above with prefix (#) as header/footer cell content. Any html also can be added to it, like: <b>Total:</b> {#stat_total}.
"FAST" mode for some operations
Starting from v.1.5 you can turn on "FAST" mode during some operations in grid. This enables it to complete these operations much faster because of skipping render stage for each operation and moving it to the end of chain. Use startFastOperations to start this mode and stopFastOperations to stop it (all events will be skipped between start and stop).
