JavaScript API Reference

TreeGrid v5.5

 

This document describes API objects, events and functions to control TreeGrid from JavaScript on client side. The API is needed only to advanced use of TreeGrid, all basic settings can be done by TreeGrid XML data format.

This document describes Extended API and Simple API for the TreeGrid.

Simple API is included in all licenses. Extended API is not included in any license and must be purchased apart.

Every property and function in JavaScript is public, but due to compressing and coding of script are visible just these.

ro means read only property in runtime – you must not change its value.

Members in blue are most important and are also in Simple API.

Members in green are also in Simple API.

Members in brown are important, but are in Extended API only.

Other members in black are in Extended API only.

Grayed members are now disabled.

 

TreeGrid data structure

 

In TreeGrid rows are represented as standard object HTMLElement and these elements are grouped to tree as done in input XML data. In Extended API you can iterate through rows as through any HTMLDocument. Every row has standard properties parentNode, nextSibling, previousSibling, firstChild, lastChild, childNodes and so on. But for iteration use predefined methods, as GetNext, GetNextVisible and so on rather then nextSibling or getElementsByTagName, because it is much faster. And for manipulating rows also use predefined functions, not HTMLElement methods.

In this documentation, the row object is named as TRow, but this object in fact does not exist.

 

All attributes loaded from XML data are in rows represented as properties with the same name as in Internal format (name consists from column name + property name). For example you can access row.Selected or row.Added. There is not predefined type for attributes, it can be string or number, depends on many factors. Therefore if you expect boolean value, you cannot test it as if(row.Selected) but if(row.Selected-0). Some attribute types are converted to internal representation (Enum is Array from 1, CalcOrder, SortCols, SortTypes, GroupCols, GroupTypes are Arrays from 0, Formula and Action are functions). For many attributes is better to read them by predefined methods as CanEdit, CanFocus and so on. Most of row’s attributes are expected to be read only, thus don’t change their values directly. For list of all possible attributes see  tag <I> and cell descriptions.

Generally, use predefined functions (if any) to read or change row’s attribute values instead of accessing them directly.

Also use these properties as read only if possible. To get row’s attribute use global function Get rather then direct access to attribute.

 

Rows are in Extended API in three root HTMLElements, XH (head rows), XF (foot rows), XB (body rows). XH and XF have only immediate child rows <I> as fixed rows. In XB are immediate children pages <B> and their children are rows <I>. If TreeGrid don’t use paging, XB has one <B> child with all rows.

Header is represented as single HTMLElement in XHeader.

 

All other XML data (defaults, columns, panel, toolbar, pager, configuration menu, language texts) are represented as JavaScript object (or arrays of these objects accessed by name) with properties of same name as XML attributes. These properties has converted type, therefore numbers are always numbers not strings. But it depends on property value not on expected type (the conversion is universal).

 

Grid configuration (tag <Cfg>) is filled to properties of basic TGrid object. TGrid object has all properties named as <Cfg> tag attributes. Values are also converted by their value types.

 

In all functions columns are identified by its name (given in XML, <C Name=””>). By this name column object can be got from TGrid.Cols array.

 

In HTML table is every row represented by one <tr> tag for every section (left columns, variable columns, right columns), see TreeGrid layout. You can access row’s sections by GetRow function and cell by GetCell function.

 

Any grid on page can be accessed from global JavaScript array Grids. By its Index or by its id.

 

Global properties

 

TGrid ro Grids [id/idx]      This is global array of all grids on page. Is indexed by grid index (from 0) or by grid id (string)

                                               Members are added by creating grids on start or by function TreeGrid ( ). Every call adds one object with index++.

                                               Existing grid can be added by function SetIdentity ( ) and removed by DelIdentity ( ).

TGrid Grids.Active            Pointer to active grid under the mouse cursor. It processes mouse wheel events.

TGrid Grids.Focused         Pointer to focused grid, processes key events. If you want to process key events in other controls, set it to null.

int Grids.CookieExpires  When configuration in cookies expires, 0 (default) never, 1 only this session, >1 after xxx seconds, or can be of type Date – exact expiration date.

string Grids.CookieParam              Other cookie parameters (path, domain, secure) in string, starting with ‘;’. For example “; path=/”.

int Grids.NoTryActiveX  When set to 1 in IE does not try to create ActiveX objects, event if it is possible and uses slower script XML parsing,

but don’t show any message to a user about ActiveX. See example Examples/Html/SubmitNoActiveX.html.

This property has sense only if is not used AJAX and all data, include Defaults.xml and Text.xml, are included in HTML page.

char Grids.CharCodes[]   If you would like to better control sorting, grouping and filtering strings you can define this array.

                                               If this array is defined, all strings before sorting, grouping or filtering are modified by this array. Defining this array can slow down sorting, grouping and filtering.

                                               It contains array of characters to replace characters in string.

                                               For example you can set Grids.CharCodes[‘a’] = ‘b’, this means that all characters ‘a’ will be replaced by ‘b’ for sorting, grouping and filtering.

                                               Use rather <C CharCodes/>.

 

Global functions

 

TGrid TreeGrid (TDataIO D, string tag = “”, string id = “”)    Creates and renders the grid. Connects the grid to the given data D.

                D is object with data settings, it corresponds to <treegrid> tag attributes. TDataIO has the same properties as <treegrid> tag, see documentation.

If the <treegrid> attributes contain “_”, this means new sub-objects in TDataIO,

for example “Data_Url” means D.Data.Url or Upload_Param_F1 means D.Upload.Param.F1.

You can create it as new TDataIO object with predefined default settings.

                D can be also of string type. In this case it contains full XML source for TreeGrid to create from. And TreeGrid cannot upload data.

tag is an id attribute of main tag or main tag object itself (usually <div>) to render grid to, this is required attribute.

id is the unique id of the grid, used to identify it, especially in saving configuration to the cookies. It can be undefined if set in downloaded data.

This function also sets the grid identity.

Function returns created TGrid object. Remember, creating and rendering is asynchronous, thus at the moment of function return, the grid is not fully prepared yet.

                After finish will be fired OnRenderFinish and OnRenderPageFinish or OnLoadError event.

void StartTreeGrid (Event event) Starts creating grids from HTML tags <treegrid>. By default it is called from window.onload event.

You can also use this function to create grid on the fly instead of TreeGrid function.

Just create some <treegrid> tag as inner HTML of <div> tag you want to render grid to and call StartTreeGrid().

The function is asynchronous, in time of return, the grids are not created yet.

Use OnRenderFinish or OnRenderPageFinish events to catch the end of grid creating.

This function creates treegrid in place of <treegrid> tag and destroys it, so it can be called as many times as you want.

object Get (TRow row, string attr)  Returns value of row’s attribute. Remember, all attributes are often of string types. If row has not this attribute set, it returns default value.

bool Is (TRow row, string attr)        Returns true if row’s attribute has “1” value. Remember, all attributes are often of string types.

If row has not this attribute set, it returns default value.

void SetEvent (string name, string id, function func)                              Sets TreeGrid event handler for grid with given id.

                Use it, if you have more grids and want to call for every grid different function.

                name – event name like “OnClick”, id – id of the grid, func – any JavaScript function to be called for event raised.

                If id is null, the function will be called for all other grids then for that have attached the event handler by SetEvent.

                Example:

                               Standard way:     Grids.OnClick = function(G){ if(G.id=="G1") alert("G1 clicked"); if(G.id=="G2") alert("G2 clicked"); }

                               New way:             SetEvent("OnClick","G1",function(){ alert("G1 clicked");} );

SetEvent("OnClick","G2",function(){ alert("G2 clicked");} ); 

                Do not use both ways together, if you set Grids.OnClick, you cannot set it also by SetEvent and vice versa.

                SetEvent is useful also when using automatic merging web pages like by Java portal - JSR-000168 Portlet.

                ! For events that return by default another value than false or null (OnRowFilter, OnGetClass) you have to define default event handler for all grids by calling it with null id.

void AddEvent (string name, string id, function func)                            Adds TreeGrid event handler for grid with given id. If id is missing, adds it for all grids.

                With this function you can have more handlers for one event and you can add and delete them dynamically

                Must not be used with SetEvent function. Must not be used with standard event assignment by Grids[name]

                Calling order of attached events is expected to be random.

                The return value for event is the first non null return value from some handler.

                This function slightly slows event execution.

void DelEvent (string name, string id, function func)                              Removes TreeGrid event handler added by AddEvent function.

                It removes only event added by AddEvent with all three parameters the same as when calling DelEvent.

 

           

Format – Independent functions, can be overridden to change data conversion

string DateToString (Date date, string format)                         Converts date to string according to format string as in function ToString() in C#.NET.

                                                                                                              date can be string, will be converted to date by standard Date(string).

                If format is missing, uses English format “mm/dd/yyyy hh:mm:ss”, for today uses “hh:mm:ss”, for 00:00:00 uses “mm/dd/yyyy”, seconds are omitted if is 0.

Date StringToDate (string str, string format)                            Converts string to date according to format string as in function ToString() in C#.NET.

If format is missing, converts str as in standard format for date “d.m.y”, “d.m”, “m/d/y”, “m/d”, “y-m-d”,”m-d” and time “hh:mm:ss”, “hh:mm”

and for date and time combines these formats separated by any other character

string NumberToString (Number num, string format)            Converts number to string according to format string as in function ToString() in C#.NET.

Number StringToNumber (string str)                                          Converts number to string

bool KeyInt (Event event, string Value)                                      Tests pressed key if can be added into integer number

bool KeyFloat (Event event, string Value)                                 Tests pressed key if can be added into floating point number

bool KeyDate (Event event, string Value)                                   Tests pressed key if can be added into date/time value

 

Functions – Independent helping functions

object GetElem (string id)                                                              Returns htlm element by its id (returns document.getElementById)

int GetKey (Event event)                                                                Returns pressed key (unicode code) in the event

Array [2] GetWindowSize ()                                                           Returns size of browser’s window, returns [width, height]

Array [2] GetWindowScroll ()                                                       Returns amount of scroll of browser’s window, returns [dX,dY]

Array [2] EventXYToElement (Event event, object elem )     Converts event.clientX, event.clientY to coordinates relative to elem. Returns [X,Y]

Array [2] ElemToParent (object elem, object parent)              Returns relative position of element in its parent. Returns [X,Y]

void CancelEvent (Event event, int type = 0)                             Cancels propagation and prevents default of event. If type==1 cancels propagation only, 2 prevents default only.

Style GetStyle (object Elem)                                                          Returns computed style of the element.

Document CreateXML (string str)                                                Creates XML document from string. This document can be iterated by DOM functions.

In all browsers all its nodes has property xml which returns the node as XML string.

object CopyObject (object o)                                                         Creates deep copy of any value.

void ShowHTML (string HTML, string name)                         Opens browser’s window named name with HTML content. If HTML does not begins with ‘<’ shows it as text.

void SaveCache (string id, string val)                                          Saves value to persistent cache according to given id. Only for IE 5+ and Firefox 2+

You can also redefine this function to do your own caching mechanism when set <Cfg PersistentCfg>

string LoadCache (string id)                                                          Loads and returns value from persistent cache saved by SaveCache function.

 

Events

 

Events in TreeGrid are defined as methods of global Grids object. If this event method is not declared, event is not fired.

You can create new event in this way: Grids.OnGetColor = function(G,row,col,r,g,b,type){ /*your code*/ };

 

Style events

string OnGetColor (TGrid grid, TRow row, string col, int r, int g, int b, int type)               Called for getting state color of the cell. If col is null, color is for whole row.

r,g,b are predefined colors for this state. type = 0 – normal row, 1 – focused cell, 2 – edited cell. Returns string color for style change (“#RRGGBB” or “rgb(r,g,b)”).

Can return null to use r,g,b values unchanged. Returned color is result color for the cell or row and is not modified according to state

int OnGetDefaultColor (TGrid grid, TRow row, string col, int rgbcolor)              Called to get default color for the cell or row. rgb is predefined color (#RRGGBB)

                Returns new integer #RRGGBB color or null to use default. The returned color is modified according to row state.

string OnGetClass (TGrid grid, TRow row, string col, string cls)            Called for getting class attribute for cell or for cell input control. cls see file Grid.css.

                grid – index of grid (from 0), row, col – cell, cls – name of default style for this cell. row can be grid.XHeader for caption, col can be “Panel” for button panel.

                returns new name of style class (without leading ‘.’) or back cls. Remember, one cell or row has more then on style class, don’t change all these to one.

                ! Don’t return class with another extents (padding,border,...) than original class ! Don’t use classes with margin properties !

string OnGetType (TGrid grid, TRow row, string col, string type)         Called for getting cell type. Returns new type or type.

string OnGetFormat (TGrid grid, TRow row, string col, string format, bool edit)             Called for getting cell format. Returns new format or format.

                if edit is false returns standard format, for true returns edit format

string OnGetEnum (TGrid grid, TRow row, string col, string[] enum) Called for getting enum array for enum cell. Returns new enum array or enum.

bool OnCanEdit (TGrid grid, TRow row, string col, bool can)                                Called before start editing cell. ce is predefined result.

Returns true to continue editing, false for prohibit editing or can.

bool OnCanEditDate (TGrid grid, TRow row, string col, Date date)                     Called when displaying date picker to permit only some dates to select by user.

string OnGetDefaults (TGrid grid, TRow row, string col, string defaults)            Called before displaying menu for Button type Defaults.

                Returns original or modified defaults string (it is first character separated array in string).

 

 

State events

type OnValueChanged (TGrid grid, TRow row, string col, type val)      Called before cell values is changed by user edit. Return new value or val.

void OnAfterValueChanged (TGrid grid, TRow row, string col)            Called after cell values is changed by user edit, only if value was changed to another.

int OnResultMask (TGrid grid, TRow row, string col, string val)           Called when value collide with ResultMask

                Returns 0 – default action, 1 – suppress default action, 2 – save value and stop edit, 3 – don’t save value and stop edit

void OnRowMoveToGrid (TGrid grid, TRow row, TGrid togrid, TRow torow, bool copy)               Called after moving or copying row to another grid.

Called from function MoveRowsToGrid ( ).

                New row (torow) is positioned yet, but not displayed. Old row (row) is still set and visible. If copy = true, old row will not be hidden.

void OnRowMove (TGrid grid, TRow row, TRow oldparent, TRow oldnext)        Called after row have been moved inside one grid.

Row is still displayed in old position but have new settings. oldparent is original parent of the row, oldnext is original next sibling.

bool OnStartDrag (TGrid grid, TRow row, string col, bool more)          Called before the row is being dragged. Return true to suppress default behavior.

                row is the caught row, col is column where the row is caught, more is true when more selected rows will be dragged together.

int OnEndDrag (TGrid grid, TRow row, TGrid togrid, TRow torow, int type, int X, int Y)                Called after the dragged row is dropped. It is called for any drop.

grid, row – dragged row, togrid, torow – drop target, type - 0 – cannot drop, 1 – in front of torow, 2 – to the end of children of torow, 3 – after torow

                X, Y – mouse cursor position on screen (related to browser window)

                togrid is never null, it is the last grid under mouse cursor. torow is null when no row is under mouse cursor.

Return new type or type. Remember, you must return the given type to permit dropping unchanged.

int OnCanDrag (TGrid grid, TRow row, TGrid togrid, TRow torow, int type)      Called during dragging row above other row to find out if and how row can be dropped. 

grid, row – dragged row, togrid, torow – drop target, type - 0 – cannot drop, 1 – in front of torow, 2 – to the end of children of torow, 3 – after torow

Return new type or type. Remember, you must return the given type to permit dropping unchanged.

This event controls dropping. To control which rows can be dragged (caught), set the row attribute CanDrag or set <Cfg Dragging> for whole grid or use OnStartDrag event.

void OnRowDelete (TGrid grid, TRow row, int type) Called before deleting every row – if row is marked as deleted. Does not fire when undeleting row.

Fires for every row being deleted, even for its children. type = 1 delete row, 2 delete row because its parent is deleted

If row is really deleted by DelRow ( ), event is not fired !

int OnCanRowDelete (TGrid grid, TRow row, int type)            Called before row is deleted or undeleted. Called to find out if and how can the row be deleted. Not called for its children.

                type = 0 – cannot delete, 1 – user must confirm deleting, 2 - delete, 3 – undelete. Returns new type or type.

                If fires, when deleting selected rows, type = 1 has no meaning.

bool OnCanRowAdd (TGrid grid, TRow parent, TRow next)                  Called before row is added to find out if can be added to this position. Called from control panel.

                parent is parent row in tree or page for root row. next is next row behind the row in their parent or null if row is added to the end of the parent children.

void OnRowAdd (TGrid grid, TRow row)                                     Called after the row is added (from control panel) but before it is displayed. Usually to change default values.

void OnRowCopy (TGrid grid, TRow row, TRow source, bool empty)                  Called after the row is copied from source row. empty is true if values were not copied.

bool OnExpand (TGrid grid, TRow row)                                      Called before the row is expanded or collapsed. Return true to suppress action.

string[2] OnPrint (TGrid grid)                                                        Called before grid is printed. Return true to cancel printing or own print.

Or return string array with HTML prefix [0] and HTML postfix [1] to add to <body> when printing.

bool OnPrintFinish (TGrid grid, Window window)                   Called after print report is created and before the printing dialog is displayed.

                window is browser’s window that contains the report.

                You can also use this event to get back changes you done in OnPrint event (for example changes in grid.Img setting).

                Return true to suppress default action. You can call w.print() in this event and do some action after, for example to close the window.

string OnSetRowId (TGrid grid, TRow row, string newid)        Called when new id attribute is generated for the row. Returns new id. The row has still old id.

                The newid and returned id is value for row id attribute. It is full id, includes all parts and optionally parent id.

string OnGenerateId (TGrid grid, TRow row, string newid)     Called when new unique part of id is generated or updated for the row. Returns new id value.

                The newid and returned id is the generated part of id, this is the value of the last attribute from IdNames list.

void OnColResize (TGrid grid, string col)                                   Called after column is resized, by user or column with relative width.

void OnColMove (TGrid grid, string col)                                     Called after column is moved to another position

void OnResizeMain (TGrid grid)                                                   Called after main tag is resized by user.

void OnScroll (TGrid grid, int hpos, int vpos, int oldhpos, int oldvpos)               Called after body was scrolled

hpos is new scrollLeft, vpos is new scrollTop, oldhpos is original scrollLeft, oldvpos is original scrollTop, all in pixels.

void OnDisable (TGrid grid)            Called before grid is disabled (and modal message is shown). Can be called also for already disabled grid.

void OnEnable (TGrid grid)             Called after grid is enabled (and modal message is hidden)

void OnShowDialog (TGrid grid, TRow row, string col, HTMLElement Tag)       Called after the dialog or menu for the cell is displayed, Tag is HTML element with the dialog.

void OnShowCfg (TGrid grid, HTMLElement Tag)                    Called after configuration menu is displayed, Tag is HTML element with the menu.

void OnShowColumns (TGrid grid, HTMLElement Tag)          Called after menu for columns visibility is displayed, Tag is HTML element with the menu.

bool OnEvent.... (TGrid grid, TRow row, string col)                   Called when this event raised before any its action is called. Return true to suppress processing event actions.

                The name of the handler consists of the full event name including prefix and target.

                This handler is not called for parent events if they are called.

                row, col is cell that the event is related to. For the key events it is focused cell, for mouse events it is the actual cell.

                For example Grid.OnEventClickDefaults = function(G,row,col){ if(!Get(row,col+”Defaults”)) { alert(“The cell has no defaults !”); return true; } }

bool OnSetStyle (TGrid grid, string stylename)          Called before the grid style is set to stylename. Return true to suppress changing style.

void OnAfterSetStyle (TGrid grid, string stylename)                Called after the grid style is set to stylename.

               

Function events – filter, sort, search, group, calculations,...

bool OnCanFilter (TGrid grid, bool start)                                   Called when grid will be re-filtered. You can provide own filtering and return false.

start is true when called by starting grid

void OnFilterFinish (TGrid grid)                                                   Called after grid was re-filtered. Called only for filtering on client.

bool OnRowFilter (TGrid grid, TRow row, bool show)             Called when filtering row, show is the filter result. Must return if row will be visible or not.

type OnGetFilterValue (TGrid grid, TRow row, string col, type val)     Called to get value for filtering and searching, val is predefined value, returns val or new value.

 

bool OnSearch (TGrid grid, string Action, bool Show)             Called when searching in grid starts after user action. Return true to suppress default searching.

                                                                                                              Action can be Filter, Select, Mark, Find, Clear, Help, Refresh.

void OnSearchFinish (TGrid grid, string Action, bool Show) Called after search in grid finished, all changes are already visible.

int OnRowSearch (TGrid grid, TRow row, string col, bool found, function func, type userdata)   Called when searching in row.

col is column cell when is searching if set searching in cells - 1.bit of SearchType to 1, otherwise it is null

found is the search result. Must return new found value. 1 – found, 0 – not found, -1 not applicable (it will not be selected but also not be hidden by filter)

if set col (searching in cells), the OnRowSearch can also return column name as the cell found

func is caller function for searching row that resulted found. it has prototype func (TRow row, string col,  type userdata)

func returns -1 if cannot search, 0 if not found or 1 if found when searching in row or column name if found when searching in cells

The func and userdata parameters can be used for searching in other rows then actual. Remember from the func is called the OnRowSearch event

userdata is null in default call, use it to mark custom calling to avoid recursion cycle. Example using func and userdata:

Grids.OnRowSearch = function (G,row,col,found,F,type){ // This function searches in children to mark/unmark parent row

if(type) return found;             // to avoid recursion cycle

if(!row.firstChild) return -1;                               // not applicable for children

for (var r=row.firstChild;r;r=r.nextSibling) if(F(r,col,1)>0) return 1;

// Searches in children, if at least one found, parent is marked as found

return 0; }

 

int OnSort (TGrid grid, string col)                                                 Called when sorting grid after user action.

Return -1 to suppress default sorting completely, return 1 to suppress sorting only and let change sort icon.

col can be null if was called from control panel. Here you can call ChangeSort to modify sorting (in this case you have to return -1).

For example this code always sorts according to column named ‘B’ as second column:

Grids.OnSort = function (G,col){

var type = G.SortCols[0]==col?!G.SortTypes[0]:0;

if(!col) { col = G.SortCols[0]; type = G.SortTypes[0]; }

if(col!='B') { G.ChangeSort(col+",B",(type-0)+",0"); return -1; }

}

void OnSortFinish (TGrid grid)                                                     Called after grid was re-sorted. Called only for sorting on client.

type OnGetSortValue (TGrid grid, TRow row, string col, type val, bool desc)    Called to get value for sorting and grouping, val is predefined value, returns val or new value.

                desc is true for descending sorting. Now this event is called only for sorting in string columns !

void OnSetPageName (TGrid grid, TRow page)         Called when are being generated page names for right side pager after sorting or grouping.

                page is given page, read and set its properties page.Name (HTML, page name displayed in pager) and page.Title (text, tooltip for page item on pager).

string OnGetPageNameValue (TGrid grid, TRow row, string col, string val)     Called to get value used for creating page names in right side pager val is predefined value, returns val or new value.

bool OnGroup (TGrid grid, string[] Cols, int[] Types, string Main)     Called when grouping grid after user action. Return true to suppress default grouping.

                Cols is new value for GroupCols, Types is new value for GroupTypes and Main (can be null) is new value for GroupMain.

void OnGroupFinish (TGrid grid)                                                 Called after grid was re-grouped in data, but before are changes visible in grid.

string OnGetGroupDef (TGrid grid, string col, string def)      Called to get default row for the group when grouping according to column

                col is column name, def is predefined name of default. Return new name of default or def.

 

type OnGetCopyValue (TGrid grid, TRow row, string col, type val)      Called to get value for copy to clipboard by Ctrl + C, val is predefined value, returns val or new value.

string OnGetExportValue (TGrid grid, TRow row, string col, string str)              Called to get value for export to Excel

                str is html tag ending character (‘>’), so to return just string return str+your_value and to return formatted number return your_format+str+your_value.

bool OnCalculate (TGrid grid, bool show, TRow row, string col)           Called for custom calculations. Return true to suppress default calculations.

                Define this event if you want to calculate cells in special order that cannot be covered by CalcOrder.

                Called for initial calculation or for recalculation of whole grid after reload or filter is applied. From Calculate and Recalculate methods.

                If row is set, it is called to calculate only row’s children after loading of page. If col is set, it is a called after some cell changed to recalculate appropriate formulas.

                In custom calculations you cannot use predefined formulas, you just have to provide your owns to calculate cells.

                And for iteration cells use GetFirst and GetNext to iterate all rows or DOM attributes firstChild and nextSibling to iterate row’s immediate children.

                To get fixed rows use GetFixedRows method. You can also test row’s attributes Visible and Deleted. Or any other row’s attribute.

bool OnPaste (TGrid grid, TRow[] rows, string[] cols, int startcol, string pastedtext)        Called before cell values are pasted by Ctrl+V from clipboard.

Return true to suppress default action.

                rows are rows to paste values into, cols are affected cols in that order, start is first column from cols where to start pasting (columns before are ignored),

pastedtext is string being pasted, rows are separated by CRLF, CR or LF, cells are separated by tabulator (\t, 09 ASCII).

The rows do not contain rows that will be added if Focused has set 8 or 12.

It is possible to change rows and cols array to paste the values to other cells.

If any array is modified by this function, it must be continuous without null values a must have correct length.

void OnPasteFinish (TGrid grid, TRow[] rows, string[] cols, int startcol)              Called after cell values are pasted from clipboard, parameters see OnPaste event.

bool OnExport (TGrid grid, string data)      Called after the export is created and before it is sent to server. data is the created export. Return true to suppress the export.

bool OnAutoFill (TGrid grid, TRow r1, string c1, TRow r2, string c2, rdir, cdir)                Called after cell range is selected by used in action FillCells/Row/Col, before the standard filling is done.

                r1,c1,r2,c2 is the selected cell range. r1,c1 is always the firstly clicked cell.

rdir is 0 when r2 is under r1 and 1 if r2 is above r1. cdir is 0 when c2 is right from c1 and 1 when c2 is left from c1.

                This function can be used to do to any operation in cell range created by dragging.

                Return true to suppress default behavior.

type OnAutoFillValue (TGrid grid, TRow row, string col, TRow orow, string ocol, type val, type prevval, int rowpos, int colpos)        Called when auto filling cell values by dragging by action FillCells/Row/Col, like in Excel.

                row, col is cell to fill; orow, ocol is base cell (the first cell dragged); val is predefined value to be filled.

                prevval is previously filled (returned) value, for the base cell is null.

rowpos, colpos is distance from the actual cell from the base cell = base cell has 0,0. rowpos is negative when filling up and colpos when filling left.

Returns new value or val.

For example: Grids.OnAutoFillValue=function(G,row,col,orow,ocol,val,old,ri,ci){return val+ri+ci;} – fills with increased values right down and decreased top left.

 

Click and key events

bool OnButtonClick (TGrid grid, TRow row, string col)           Called after user button click the button on the right of the cell.

                If called from menu Defaults, can return false to not hide dialog if this events handler opened another dialog.

                If called from standard button click, the return value is ignored.

bool OnLinkClick (TGrid grid, TRow row, string col, string url, string target)    Called after user clicks link at cell of type Link or Img.

                Returns true to suppress default action. url is url opened in browser, target is target browser’s window.

bool OnClick (TGrid grid, TRow row, string col, int x, int y, bool handled, Event event)                 Called after click to cell.

row==grid.XHeader for header, col==”Panel” for panel. row and col are never null.

                x, y is cursor position relative to the cell, handled is always false since V5.5 and should be ignored.

                event is standard MouseEvent to get for example information about Ctrl/Alt/Shift keys or other information about click.

Returns true to suppress default Click action; The AfterClick action is called regardless on this returned value. This event is called after BeforeClick action.

                This event has been changed since V5.5. Now it is called always before any predefined click action and returned true suppresses every defined Click action!

bool OnDblClick (TGrid grid, TRow row, string col, int x, int y, Event event)                    Called after grid is double clicked.

row==grid.XHeader for header, col==”Panel” for panel. row or col can be null for double click outside the cells.

                x,y is cursor position relative to the cell. event is standard MouseEvent

Returns true to suppress default DblClick action; The AfterDblClick action is called regardless on this returned value. This event is called after BeforeDblClick action.

bool OnRightClick (TGrid grid, TRow row, string col, int x, int y, Event event)                 Called after grid is right clicked.

row==grid.XHeader for header, col==”Panel” for panel. row or col can be null for right click outside the cells.

x,y is cursor position relative to the cell. event is standard MouseEvent

Returns true to suppress default RightClick action; The AfterRightClick action is called regardless on this returned value. This event is called after BeforeRightClick action.

You can use it for example to display your custom popup menu in such way:

Grids.OnRightClick = function(G,row,col,x,y){

var names = ["item1","item2","item3"];

Grids[0].ShowMenu (row, col, names, null,

   function func(index,G,row,col,UserData) { alert("User clicked to "+names[index]+", user data is "+UserData); }

   ,0,"",x,y,"my data");

return true;

}

bool OnContextMenu (TGrid grid, TRow row, string col, int index, string item)                Called when user clicks to context menu set by Menu attribute.

                index is menu item index (from 1), item is item name from Menu array an user clicked to.

bool OnKeyDown (TGrid grid, char key, Event event)                             Called when user hold down key in focused grid. Return true to suppress default action

bool OnKeyPress (TGrid grid, char key, Event event)              Called when user presses key in focused grid. Return true to suppress default action.

bool OnTabOutside (TGrid grid, int move)                                Called when user presses tab key on first or last cell in grid to change focus to another control.

                                                                                                              Return true if focus moved and grid lost it.

move is 1 to forward move (last cell), -1 to backward move (first cell).

void OnFocus (TGrid grid, TRow row, string col, TRow orow, string ocol, int pagepos)                   Called when cell is focused, row, col is actual (new) focused cell.

orow, ocol is previously focused cell. All rows and cols parameters can be nulls.

pagepos is not null if row is not rendered page or row with children, in this case it is position on the page. If paging is not used, it is always null.

                Focusing is moving cursor to row’s cell. By mouse click or by arrow keys or by tab key. Don’t confuse selecting and focusing row.

void OnSelect (TGrid grid, TRow row, int type)                          Called before the selection state of the row is changed. type = 0 (select), 1 (unselect), 2 (change)

                Selection is done by user by clicking on row’s panel O icon or by pressing space key.

Don’t confuse selecting and focusing row. In the grid can be more selected rows, but only one focused.

bool OnSelectAll (TGrid grid)         Called before all rows are selected or unselected by click to header panel button. Return true to suppress the action.

bool OnDeleteAll (TGrid grid)        Called before all selected rows are deleted or undeleted by click to header panel button. Return true to suppress the action.

bool OnStartEdit (TGrid grid, TRow row, string col) Called before starting editing, can return true to suppress editing

object OnGetInputValue (TGrid grid, TRow row, string col, object V) Called to convert cell value to input string

                V is object with these three properties: Value, Type and Mask. You can change any of them and return V back.

string OnSetInputValue (TGrid grid, TRow row, string col, string val) Called to convert input string back to cell value, returns new or original val.

int OnEndEdit (TGrid grid, TRow row, string col, bool save, type val) Called before editing is finished

                Returns: 0 continue default action, -1 continue editing, 1 event handled and value changed and saved, 2 event handled and value was not changed

                To change edited value you should rather use event OnValueChanged. Also see OnAfterValueChanged event.

                To return 1 or 2 you must handle the event, set EditMode to 0 and refresh / recolor the cell.

bool OnShowDetail (TGrid master, TGrid detail, TRow row)  Called before master row is displayed in detail grid, can return true to suppress action

void OnShowDetailFinish (TGrid master, TGrid detail, TRow row)      Called after master row is displayed in detail grid

bool OnGoToPage (TGrid grid, TRow page, int pagepos)                       Called when grid displays another page. Return true to cancel change.

page is page (<B> tag) which will changed to,  pagepos is this page position inside body, from 0.

               

Data events

bool OnDataSend (TGrid grid, object iopart, string data, function func)            Called when request is sent to server by AJAX

                Returns true to suppress default communication. Parameters are the same as in data method Communicate ( ).

                If it does return true, must call function func (int code, object response).

bool OnDataError (TGrid grid, int code, string mess, object iopart, TRow row)               Called when got server response with error code in AJAX communication.

                iopart is part of TDataIO object, row is set to page or row for that data was downloaded.

                Returns true to suppress default alert or reload action for code==-6.

void OnDataErrorDebug (TGrid grid, int code, string mess, string html)           Called when got server response with error code in AJAX communication.

                Called independently on Debug attribute value, html is message returned from server

void OnDataReceive (TGrid grid, TRow row)                             Called when got server response with correct data in AJAX communication.

                When called grid.IO contains object with <IO> settings. Event handler function can test or modify these settings.

                The row parameter contains row or page if data for page or children was requested.

bool OnDownloadPage (TGrid grid, TRow row, function func)             Called when data for page or row’s children are requested.

                Returns true to suppress default downloading. If does return true, must call function func(int result), where result<0 is error code or 0 for ok.

bool OnReadData (TGrid grid, object iopart, function func)  Called whed data for defaults, texts, layout or body are requested by any method (AJAX, submit, ...)

iopart is one part of TDataIO object, for example Grid.Data.Layout.

If it does return true, must call function func(int result), where result<0 is error code or 0 for ok.

bool OnSave (TGrid grid, TRow row, bool AutoUpdate)          Called to submit or upload changes to the server by custom way. Returns true to suppress default data upload.

                row – if only one row was changed, this is the row to update. AutoUpdate is set to true if this event was fired from auto update.

bool OnReload (TGrid grid)                            Called from control panel to cancel changes and reload data by custom way. Returns true to suppress default reload.

bool OnCanReload (TGrid grid, int changed, bool cancel)      Called when reload is requested (when reloading or server side sorting/filtering/grouping),

called instead of confirming message to user. returns false to cancel action.

changed = &1 – grid contains changed rows, &2 – grid contains selected rows.

cancel is true if changes should be canceled, true if changes should be saved (when server side sorting/filtering/grouping). To save changes call Save function from this event.

void OnLoaded (TGrid grid)                           Called when all body data were loaded, before OnLoadError.

void OnLoadError (TGrid grid)                    Called when data cannot be downloaded and grid cannot render and shows fatal error.

bool OnRenderStart (TGrid grid)                  Called when all data are loaded and updated and rendering started. Or when called Render function.

                                                                              Return true to cancel rendering

void OnRenderFinish (TGrid grid) Called when rendering or re-rendering of grid is done. Use if you need to do some post-render actions.

                This event is fired after whole grid layout and fixed rows are rendered, but before any variable row is rendered, see OnRenderPageFinish.

void OnRenderPageStart (TGrid grid, TRow row)                     Called before page is rendered.

When used child paging, this event is fired after rendering children of any expanding row.

void OnRenderPageFinish (TGrid grid, TRow row)                  Called after page is rendered.

If grid does not use paging, firing this event means, that whole grid is fully rendered.

When used child paging, this event is fired after rendering children of any expanding row.

bool OnLoadCfg (TGrid grid)                        Called when cfg is being loaded, returns true to suppress loading. Called even if SuppressCfg set.

void OnCfgLoaded (TGrid grid)                    Called when cfg is loaded to provide own update to cfg.

bool OnSaveCfg (TGrid grid)                         Called when cfg is being saved to cookis, returns true to suppress saving. Called even if SuppressCfg set.

int OnValidateError (TGrid grid, TRow[] rows, string[] cols) Called on validation error when saving. When set Validate attribute.

Return 0 for default behavior, 1 to cancel saving, 2 to continue saving

rows and cols are invalid cells that do not match their ResultMask.

 

Toolbar events

bool OnCanShowPanelItem (TGrid grid, int index, bool show)             Called to let to hide panel icon. Returns false to hide icon.

show – if button is visible by default according to grid type and supported functions, this handler usually returns this value.

                index = 1 Save, 2 Reload, 3 Add, 4 Sort, 7 Help, 8 Expand all, 9 Collapse all, 10 Cfg, 11 AddChild, 12 Repaint, 13 Calc, 14 Columns menu, 15 Print, 16 Export

string OnGetUserPanel (TGrid grid)             Called to show user icons on panel. These icons are inserted in front of columns, cfg and help icons.

                This function returns empty string or HTML code of all user buttons. Every user button must be placed to <TD></TD> tags.               

For example: "<td><button class=GButton onclick='alert(\"User toolbar button clicked!\");'>User</button></td>".

                This event is listed only for backward compatibility, you should display your custom code in Html type toolbar cell.

bool OnPanelClick (TGrid grid, int index)                                  Called when user clicks button on control panel. Returns true to suppress default action.

                index is button index, see OnCanShowPanelItem

bool OnCanShowCfgItem (TGrid grid, int index, bool show) Called to let to hide cfg menu item from JavaScript runtime. Returns false to hide item.

show – if button is visible by default according to grid type and supported functions, this handler usually returns this value.

                index = 1 Show deleted, 2 Auto sort, 3 Auto update, 10 Mouse hover, 11 Show drag object, 12 Show left panel, 13 Show icons, 14 Show pager, 15 Show all pages

void OnCfgChanged (TGrid grid)                  Called when user presses OK button on configuration menu, after all changes have been set in data,

but before saving to cookies and before any updates in display. Fired even if user did not make changes.

void OnColumnsChanged (TGrid grid, bool[string]cols, int count)                      Called when user presses OK button on columns menu. Before any updates in data or display.

                cols are array of changed columns, with string index as column name and value as its new visibility

 

Class TGrid

 

Design / runtime properties

The instance of TGrid has all properties from data tag <Cfg>, if value is number, it is converted to number.

 

Runtime only properties

int Index                                              Unique index of grid to global array Grids. Grid gets first available index (from 0), when is created.

TCol [] Cols                                        Array of all columns accessible by their names. TCol is object with all attributes from XML <C> tag.

int RowCount                                     Count of actually rendered variable rows. This variable is set when page was rendered and is updated for every next page rendered.

                                                               For non-paging grids, you can access this variable first in OnRenderPageFinish event handler.

HTMLElement XB                             <Body> node. This contains all pages <B> with variable rows <I>, in Internal format.

HTMLElement XH                             <Head> node. This contains all head rows <I>, <Filter>, <User>, in Internal format.

HTMLElement XF                              <Foot> node. This contains all foot rows <I>, <Filter>, <User>, in Internal format.

HTMLElement XS                              <Solid> node. This contains all solid space rows <I>, <Group>, <Search>,<SimplePager>,<Toolbar>, in Internal format.

HTMLElement XHeader                  <Header> node row. This represents column titles, node is in Internal format.

HTMLElement XGroup                    <I Kind=”Group”> node. This represents grouping row, node is in Internal format. Obsolete, you should access the rows by GetRowById method.

HTMLElement XPager                     <I Kind=”Pager”> node. This represents grouping row, node is in Internal format. Obsolete, you should access the rows by GetRowById method.

string [][] Lang                                   Array of sections with texts, from node <Lang>, identified by names Lang[“section”][“ident”], for example Lang[“Alert”][“Row2”]

object [] Toolbar                               Array of toolbar settings, from node <Toolbar>, number values are converted to numbers. Instance is in ControlPanel property.

object [] MenuCfg                             Array of configuration menu settings, from node <MenuCfg>, number values are converted to numbers.

object [] Pager                                   Array of pager settings, from node <Pager>, number values are converted to numbers.

string [][3] ColNames                        Three Arrays of column names (ColNames[0] = left, [1] = variable, [2] = right), sorted by position in table

 

TRow ro FRow [null]                         Focused Row

int ro FPagePos [null]                       If FRow is typeof page (not rendered yet), there is index of focused row on this page

string ro FCol [null]                           Focused Col

bool ro EditMode [false]                  If focused cell is edited now

TRow ro ARow [null]                         Row under mouse cursor

string ro ACol [null]                          Col under mouse cursor

 

bool ro Loading [false]                    Grid is starting now, loads and prepares its data, starting is background process. After Loading is cleared, grid starts rendering.

bool Rendering [false]                     Grid is rendering now, rendering is background process

                You can set rendering to true, if you plan to show or hide many rows to speed up the action.

                After finish, you need set Rendering to false and call function SetScrollBars to update grid layout.

bool StopCalc [false]                        If true, does not refresh calculated cells after some value changed

TGridDialog Dialog [null]               Displayed modal dialog or null

TDataIO Data [empty TDataIO]    Object for connecting grid to the web server. Its parameters are the same as attributes of <treegrid> tag,

but are parsed to object arrays by char ‘_’. For example <treegrid Layout_Url> is Data.Layout.Url or <treegrid Layout_Param_P1> is Data.Layout.Param.P1.

TIO IO [empty TIO]                          Object of server response. Every communication changes this object. This contains all attributes of <IO> tag and vice versa.

TToolbar ControlPanel [object]    Instance of toolbar. Setting is in Toolbar property.

 

Column methods

int[] GetSections ( )                           Returns first and last visible section [c1,c2]. c1 is 0 if left cols are visible, 1 otherwise, c2 is 3 if right cols are visible otherwise 2.

string GetNextCol (string col)        Returns next visible column according to its position in html

string GetPrevCol (string col)        Returns previous visible column according to its position in html

string GetFirstCol (int sec)             Returns first visible column in given section or null

string GetLastCol (int sec)              Returns last visible column in given section or null

void MoveCol (string col, int pos, bool noshow)        Moves visible column to new position, inside section only. If noshow set, does not display changes.

void ChangeColsPositions (string[] leftcols, string[] cols, string[] rightcols)       Changes positions of all columns in grid and splits them to sections.

                All three arguments are Arrays of column names sorted according their positions in given section

All column names must be given. Does not show changes (re-rendering is needed by Render function) and also does not save changes to cookies.

void ShowCol (string col)                Displays hidden column. Can re-render grid, if needed.

void HideCol (string col)                 Hides visible column. Can re-render grid, if needed.

bool ChangeColsVisibility (string[] Show, string[] Hide, bool prefer=0)            Changes visibility of given columns

                Show – array of column names to show, Hide – array of column names to hide

                If column is present in both arrays, it will be shown for prefer = 0 or hidden for prefer = 1

                Returns true, if re-rendering is needed (by Render function).

                Remember, if you call this function when grid is disabled (is displaying message) you have to call SetScrollBars function after enabling grid.

TCol AddCol (string col, int sec, int pos, int width, bool show, string type, string caption, string formula, string enum)      Adds one column to the table.

                col is column name, sec is section of columns (0 – left, 1 – variable, 2 – right), position is column position in its section

                width is column width or null for automatic computing, for show = true is column displayed in table,