TMS TAdv String Grid Developers Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 194 [warning: Documents this large are best viewed by clicking the View PDF Link!]

TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
1 | P a g e
TMS TAdvStringGrid
DEVELOPERS GUIDE
Productivity feature packed grid for Delphi &
C++Builder
May 2017
Copyright © 1996 2017 by tmssoftware.com bvba
Web: http://www.tmssoftware.com
Email : info@tmssoftware.com
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
2 | P a g e
Table of contents
TABLE OF CONTENTS ........................................................................................................................................ 2
WELCOME ........................................................................................................................................................ 4
TADVSTRINGGRID AVAILABILITY ...................................................................................................................... 5
TADVSTRINGGRID DESCRIPTION ...................................................................................................................... 6
TADVSTRINGGRID MAIN FEATURES ................................................................................................................. 7
TADVSTRINGGRID USE ..................................................................................................................................... 8
TADVSTRINGGRID IMPORT & EXPORT CAPABILITIES ........................................................................................ 9
TADVSTRINGGRID SORTING CAPABILITIES ..................................................................................................... 18
TADVSTRINGGRID INPLACE EDITING .............................................................................................................. 26
TADVSTRINGGRID MOUSE AND NAVIGATION CONTROL ................................................................................ 51
TADVSTRINGGRID COLUMN SIZING ................................................................................................................ 59
TADVSTRINGGRID STYLES............................................................................................................................... 60
TADVSTRINGGRID CELL AND CELL PROPERTIES ACCESS .................................................................................. 62
TADVSTRINGGRID ROW & COLUMN METHODS ............................................................................................. 65
TADVSTRINGGRID CELL GRAPHICS ................................................................................................................. 66
USING A VERTICAL SCROLLBAR PER CELL IN TADVSTRINGGRID ...................................................................... 82
TADVSTRINGGRID HTML FORMATTED CELLS .................................................................................................. 85
TADVSTRINGGRID HTML FORMS .................................................................................................................... 90
TADVSTRINGGRID MISCELLANEOUS DISPLAY CONTROL ................................................................................. 92
TADVSTRINGGRID ROW HOVER BUTTONS ..................................................................................................... 99
TADVSTRINGGRID NODES ............................................................................................................................ 100
TADVSTRINGGRID FILTERING ....................................................................................................................... 103
TADVSTRINGGRID GROUPING ...................................................................................................................... 112
TADVSTRINGGRID PRINTING CAPABILITIES .................................................................................................. 119
TADVSTRINGGRID CLIPBOARD HANDLING ................................................................................................... 126
TADVSTRINGGRID FLOATING FOOTER USE ................................................................................................... 128
DIRECT COLUMN CALCULATIONS ................................................................................................................. 130
ADVSTRINGGRID SEARCH PANE ................................................................................................................... 131
TADVSTRINGGRID CELL MERGING ................................................................................................................ 134
TADVSTRINGGRID OLE DRAG & DROP .......................................................................................................... 136
TADVSTRINGGRID HIDDEN COLUMNS AND ROWS ....................................................................................... 139
TADVSTRINGGRID CELL FORMATTING .......................................................................................................... 141
TADVSTRINGGRID VIRTUAL CELLS ................................................................................................................ 144
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
3 | P a g e
TADVSTRINGGRID HINTS .............................................................................................................................. 146
TADVSTRINGGRID SEARCH & REPLACE TEXT ................................................................................................ 148
TADVSTRINGGRID DISJUNCT ROW, COLUMN AND CELL SELECTION ............................................................. 151
TADVSTRINGGRID CELL CHECK ARCHITECTURE ............................................................................................ 153
TADVSTRINGGRID ADD-ON DIALOGS ........................................................................................................... 155
TADVSTRINGGRID UNICODE SUPPORT ......................................................................................................... 156
TADVSTRINGGRID UNDO/REDO ADD-ON COMPONENT ............................................................................... 158
TADVSTRINGGRID COLUMN STATE PERSISTENCE ......................................................................................... 159
TADVSTRINGGRID IMPORT/EXPORT TO XLS FILES VIA TADVGRIDEXCELIO ................................................... 161
TADVSTRINGGRID EXPORT TO RTF FILES VIA TADVGRIDRTFIO ..................................................................... 166
USING THE ICELLGRAPHIC INTERFACE FOR CELLS ......................................................................................... 168
USING THE COMPONENT TADVGRIDDROPDOWN ........................................................................................ 172
CUSTOMIZING THE ITEM CLASS IN TADVGRIDDROPDOWN .......................................................................... 176
USING THE TADVGRIDHEADERLIST & TADVGRIDHEADERLISTPOPUP ........................................................... 179
TADVSTRINGGRID TIPS AND FAQ ................................................................................................................. 181
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
4 | P a g e
Welcome
Welcome to the TAdvStringGrid Developer's Guide, created by tmssoftware.com.
At tmssoftware.com, we strive to produce world class software components that enable developers
to produce quality software for the most demanding of environments.
Our innovative component suites are designed to be extensible, easy to use and design time rich.
We provide full source code to enable seamless integration of our components with our customers'
projects.
All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic,
electronic, or mechanical, including photocopying, recording, taping, or information storage and
retrieval systems - without the written permission of the publisher.
Products that are referred to in this document may be either trademarks and/or registered
trademarks of the respective owners. The publisher and the author make no claim to these
trademarks. While every precaution has been taken in the preparation of this document, the
publisher and the author assume no responsibility for errors or omissions, or for damages resulting
from the use of information contained in this document or from the use of programs and source
code that may accompany it. In no event shall the publisher and the author be liable for any loss of
profit or any other commercial damage caused or alleged to have been caused directly or indirectly
by this document.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
5 | P a g e
TAdvStringGrid availability
TAdvStringGrid is available as VCL component.
VCL versions:
TAdvStringGrid is available for Delphi 7, 2007,2009,2010,XE,XE2,XE3,XE4,XE5,XE6,XE7,XE8,10
Seattle, 10.1 Berlin, 10.2 Tokyo and C++Builder
2007,2009,2010,XE,XE2,XE3,XE4,XE5,XE6,XE7,XE8,10 Seattle, 10.1 Berlin, 10.2 Tokyo
TAdvStringGrid has been designed for and tested with: Windows 2008, XP, Vista, Windows 7,
Windows 8, Windows 10.
TAdvStringGrid supports 32bit and 64bit platform types when compiled with Delphi
XE2/XE3/XE4/XE5/XE6/XE7/XE8/10 Seattle/10.1 Berlin/10.2 Tokyo
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
6 | P a g e
TAdvStringGrid description
High productivity & feature-packed grid control.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
7 | P a g e
TAdvStringGrid main features
Built-in flexible printing
Extensive capabilities for controlling display in cells
Easy & fine control over editing & navigation
Various file formats supported for import & export
Wide range of built-in inplace editors
Many types of graphics supported
Clipboard, drag&drop and OLE drag&drop to exchange data
3rd party support like spell checking, scripting, …
And much more...
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
8 | P a g e
TAdvStringGrid use
The TMS TAdvStringGrid component is designed to be used in the most broad types of applications
needing to display or handle data in rows and columns. TAdvStringGrid is designed as drop-in
replacement for the Borland TStringGrid component. As such, it is fully compatible with TStringGrid
and inherits all functionality of the base class TStringGrid. For documentation on this base
functionality, we refer to the Borland documentation. This manual therefore assumes the developer
is familiar with the functionality of TStringGrid. For example, a grid cell value can be set with
grid.Cells[col,row]: string just like in TStringGrid. The focused cell can be set with grid.Row:
integer & grid.Col: integer properties, also just like TStringGrid.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
9 | P a g e
TAdvStringGrid import & export capabilities
The TMS TAdvStringGrid component can save and load its data in many different formats explained
here:
internal
CSV
DOC
XLS
XML
MDB
ASCII
Fixed
BIN
HTML
stream
Binary stream
RTF
Properties that have effect on grid saving and loading are:
SaveFixedCells: Boolean
When true, the contents of fixed cells are also saved and loaded. Default value is true. This applies
to both fixed columns and fixed rows.
SaveFixedRows: Boolean
When true, the contents of fixed rows are also saved and loaded. Default value is true.
SaveFixedCols: Boolean
When true, the contents of fixed columns are also saved and loaded. Default value is true.
SaveHiddenCells: Boolean
When true, the contents of hidden cells are saved. Default value is false.
SaveWithHTML: Boolean
When false, all HTML tags are removed from cell contents if these have HTML tags. Default value is
true.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
10 | P a g e
SaveWithRTF: Boolean
When true, RTF information is saved along the cell value. When false, all text formatting is removed
before saving the cell value.
SaveVirtCells: Boolean
When true, the displayed value of a cell is save. When false, the real grid cell value is saved. As
explained further in this guide, a grid cell value can be dynamically altered for display using the
OnGetDisplText event. With this public property SaveVirtCells, it can be choosen which value will be
saved.
OnFileProgress: TGridProgressEvent(Sender:TObject;progress: smallint);
This event is triggered to return the percentage of completion during save and load operations.
Overview of methods
Files
procedure SaveToFile(FileName: String);
procedure LoadFromFile(FileName: String);
SaveToFile saves cell data and column widths to a proprietary file format. LoadFromFile loads cell
data and column widths from a proprietary file format.
Binary files
procedure SaveToBinFile(FileName: String);
procedure LoadFromBinFile(FileName: String);
SaveToBinFile saves cell data and cell properties to a proprietary file format. LoadFromBinFile loads
cell data and cell properties from a proprietary file format.
Streams
procedure SaveToStream(Stream: TStream);
procedure LoadFromStream(Stream: TStream);
SaveToStream saves cell data and column widths to a stream. LoadFromStream loads cell data and
column widths from a stream.
Example: copying grid information from grid 1 to grid 2 through a memorystream:
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
Grid1.SaveToStream(ms);
ms.Position := 0; // reset stream pointer to first position
Grid2.LoadFromStream(ms);
ms.Free;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
11 | P a g e
end;
Binary streams
procedure SaveToBinStream(Stream: TStream);
procedure LoadFromBinStream(Stream: TStream);
procedure SaveRectToBinStream(Rect: TRect; Stream: TStream);
procedure LoadAtPointFromBinStream(Point: TPoint; Stream: TStream);
SaveToStream saves cell data and cell properties to a binary stream. LoadFromStream loads cell
data and cell properties from a binary stream. SaveRectToBinStream saves only cells with in
rectangle coordinates specified through the Rect parameter. Finally, the method
LoadAtPointFromBinStream loads cell data and cell properties from the binary stream starting from
the specified cell coordinate as first top left cell of the data loaded.
CSV files
procedure SaveToCSV(FileName: String);
procedure LoadFromCSV(FileName: String; MaxRows: integer= -1; IgnoreRows:
integer=-1);
procedure LoadFromStream(AStream: TStream; MaxRows: integer= -1;
IgnoreRows: integer=-1);
procedure AppendToCSV(FileName: String);
procedure InsertFromCSV(FileName: String; MaxRows: integer= -1; IgnoreRows:
integer=-1);
SaveToCSV saves cell data to a CSV file. LoadFromCSV loads cell data from a CSV file. The method
LoadFromCSVStream loads cell data from a stream as if the stream contains data structured as in a
CSV file. AppendToCSV appends cell data to an existing CSV file. InsertFromCSV inserts cell data
loaded from the CSV file as extra rows in the grid. Note that LoadFromCSV & InsertFromCSV have a
default parameter MaxRows. Without this parameter, all rows in the CSV file are loaded in the grid.
When the 2nd parameter MaxRows is used, this sets the maximum number of rows that will be
loaded. Finally, the last parameter IgnoreRows can be used to define the number of first rows in the
CSV file that can be skipped or ignored for import.
Several properties affect the CSV methods:
Grid.Delimiter: Char;
This specifies the delimiter to use for saving and loading with CSV files. By default the Delimiter is
set to #0. With Delimiter equal to #0, an automatic delimiter guess is used to load data from the
CSV file. To save to a CSV file, the ; character is used as separator when delimiter is #0. Setting the
delimiter to another character than #0 forces the CSV functions to operate with this delimiter only.
Grid.QuoteEmptyCells: Boolean;
When true, an empty cell in the CSV file is saved as “”, otherwise no characters are written to the
CSV file.
Grid.AlwaysQuotes: Boolean;
When true, every cell value is saved with prefix and suffix quotes, otherwise quotes are only used if
the cell data contains the delimiter character. Note that when the cell data contains quotes, the
data is written with doubled quotes to the file.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
12 | P a g e
Grid.CSVTrimspaces: Boolean;
When true as default, spaces before or after values in the CSV file are trimmed. Otherwise, the
spaces are kept as-is in the grid during import.
Fixed files
procedure SaveToFixed(FileName: string;positions: TIntList);
procedure LoadFromFixed(FileName:string;positions:TIntList; DoTrim: boolean
= true; MaxRows: integer = -1);
SaveToFixed saves cell data and column widths to a text file with fixed column lengths.
LoadFromFixed loads cell data and column widths from a text file with fixed column lengths. The
TIntList parameter is a list of integer values specifying the character offsets where a column starts
in the file. TintList is defined in the AdvObj unit, so to use this, include AdvObj in the uses clause of
your form .PAS file.
Example: loading from a fixed file
var
Il: TintList;
begin
Il := TintList.Create(0,0);
Il.Add(0); // first column offset
Il.Add(15); // second column offset
Il.Add(30); // third column offset
Il.Add(40); // fourth column offset
Grid.LoadFromFixedFile(‘myfile.txt’,il);
Il.Free;
end;
Note that LoadFromFixed has two additional default parameters: DoTrim & MaxRows. When DoTrim
is false, spaces before or after words are not removed. Without MaxRows, all rows in the text file
are loaded in the grid. When the last parameter MaxRows is used, this sets the maximum number of
rows that will be loaded.
HTML files
procedure SaveToHTML(FileName: String);
procedure AppendToHTML(FileName: String);
SavetoHTMLFile saves the cell data to a HTML file and uses the grid.HTMLSettings to control the
method for saving. The cell data is saved to a HTML table. AppendToHTML appends the cell data to
an existing HTML file.
With HTMLSettings, following settings can be done:
property BorderSize: Integer
Sets the border size for the HTML table
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
13 | P a g e
property CellSpacing: Integer
Sets the cellspacing value for the HTML table
property CellPadding: Integer
Sets the cellpadding value for the HTML table
property SaveColor: Boolean
If true, grid color information is written to the HTML table
cells
property SaveFonts: Boolean
If true, grid font information is written to the HTML table
cells
property FooterFile: string
File that is to be appended after the HTML table in the
final HTML file
property HeaderFile: string
File that is inserted before the HTML table in the final
HTML file
property TableStyle: string
Sets additional HTML table style properties
property PrefixTag: string
Sets any text that should be written in the HTML file
before the table is output
property SuffixTag: string
Sets any text that should be written in the HTML file after
the table is output
property ConvertSpecialChars: Boolean
When true, special characters as >, <, & … are exported
as respectively &gt; , &lt; , &amp; …
property ImageBaseName: string;
Stes the identifier prefix for images in HTML. It is
important that, when exporting multiple different grids to
a single HTML file, that each grid uses a unique
ImageBaseName.
Property ImageFolder: string;
Specifies the folder where images that belong in the HTML
export are stored
property NonBreakingText: Boolean
When true, all text is exported as non breaking text, ie.
all spaces are exported as &nbsp;
property Summary: string
Sets the HTML TABLE summary attribute for the exported
grid
property AutoPreview: Boolean
When true, the exported HTML file is automatically
previewed in an instance of the default browser
property ExportImages: Boolean
When true, images in the grid are also exported
property Width: Integer
Sets the width percentage of the HTML table
property XHTML: Boolean
When true, the output is xHTML compatible
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
14 | P a g e
XML files
procedure SaveToXML(FileName: String; ListDescr,
RecordDescr:string;FieldDescr:TStrings);
Saves the cell data in an XML file with following structure:
<ListDescr>
<RecordDescr>
<FieldDescr[0]>Cell 0,0</FieldDescr[0]>
<FieldDescr[1]>Cell 1,0</FieldDescr[1]>
<FieldDescr[2]>Cell 2,0</FieldDescr[2]>
</RecordDescr>
<RecordDescr>
<FieldDescr[0]>Cell 0,1</FieldDescr[0]>
<FieldDescr[1]>Cell 1,1</FieldDescr[1]>
<FieldDescr[2]>Cell 2,1</FieldDescr[2]>
</RecordDescr>
</ListDescr>
procedure LoadFromXML(FileName: String; LevelToRow: Boolean = false);
Loads the grid data from an XML file. When the optional LevelToRow parameter is true, a new row
is used for every new XML node level, otherwise, XML nodes are added in additional columns.
Example:
This code snippet save a grid with 5 columns to XML and uses the text in the column headers as field
descriptors in the XML file:
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
for i := 0 to grid.ColCount 1 do
sl.Add(grid.Cells[I,0]);
grid.SaveToXML(‘mygrid.xml’, ‘xmllist’, ‘xmlrecord’, sl);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
15 | P a g e
sl.Free;
end;
A public property that is used for exporting to XML file is XMLEncoding that defaults to 'ISO-8859-1'.
This property can be used to set a different XML encoding attribute that is saved to the XML file.
JSON files
procedure SaveToJSON(FileName: String;
RecordDescr:string;FieldDescr:TStrings);
Saves the cell data in an JSON file with following structure:
{"grid":[{"row":[{"col1":"1:1"},{"col2":"2:1"},{"col3":"3:1"},{"col4":"4:1"}]}
,{"row":[{"col1":"1:2"},{"col2":"2:2"},{"col3":"3:2"},{"col4":"4:2"}]}
,{"row":[{"col1":"1:3"},{"col2":"2:3"},{"col3":"3:3"},{"col4":"4:3"}]}
,{"row":[{"col1":"1:4"},{"col2":"2:4"},{"col3":"3:4"},{"col4":"4:4"}]}
,{"row":[{"col1":"1:5"},{"col2":"2:5"},{"col3":"3:5"},{"col4":"4:5"}]}
,{"row":[{"col1":"1:6"},{"col2":"2:6"},{"col3":"3:6"},{"col4":"4:6"}]}
,{"row":[{"col1":"1:7"},{"col2":"2:7"},{"col3":"3:7"},{"col4":"4:7"}]}
,{"row":[{"col1":"1:8"},{"col2":"2:8"},{"col3":"3:8"},{"col4":"4:8"}]}
,{"row":[{"col1":"1:9"},{"col2":"2:9"},{"col3":"3:9"},{"col4":"4:9"}]}
]}
Where “row” is the record descriptor and col1, col2, col3, col4 are the field descriptors for column
1,2,3 and 4.
This is the sample code snippet that would product this JSON file:
var
SL: TStringList;
i: integer;
begin
AdvStringGrid1.LinearFill(false);
AdvStringGrid1.SaveFixedCells := false;
SL := TStringList.Create;
try
for i := AdvStringGrid1.FixedCols to AdvStringGrid1.ColCount - 1 do
SL.Add('col'+inttostr(i));
AdvStringGrid1.SaveToJSON('myfile.json','row',SL);
finally
SL.Free;
end;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
16 | P a g e
ASCII files
procedure SaveToASCII(FileName: String);
SaveToASCII saves the cell data to an ASCII file, automatically using column widths to fit the widest
data in cells available. A difference with fixed column width files is also that SaveToAscii will
correctly split cell contents across multiple lines when MultiLineCells is set True.
procedure AppendToASCII(FileName: String);
This procedure is identical to SaveToASCII, except that it appends the data to an existing file. Note
that TAdvStringGrid also comes with a component TAdvGridImportDialog. This dialog can be used to
allow the user to set the fixed column widths at runtime. From a preview dialog, this is done by
clicking to set the fixed column widths. The use of this dialog is explained further in this guide.
Access files
procedure LoadFromMDB(FileName:string; Table: string);
procedure LoadFromMDBSQL(FileName:string; SQL: string);
LoadFromMDB loads data from a table in an Access MDB file. All rows and columns are loaded in the
grid. LoadFromMDB relies on ADO and as such requires that ADO is installed on the machine.
LoadFromMDBSQL loads data from an Access table with a SQL SELECT command. Note that
LoadFromMDB is equivalent to LoadFromMDBSQL with the SELECT statement:
SELECT * from TABLE
Microsoft Word files
procedure SaveToDoc(FileName: string; CreateNewDocument: boolean = true);
This procedure saves the grid data as a table in a MS Word document. By default, this is in a new
document. When the parameter CreateNewDocument is true, a new document is explicitely
created, when false, the table will be saved in the default active Word document.
procedure AppendToDoc(FileName, Bookmark: string);
Call grid.AppendToDoc(FileName) to add the grid data to an existing MS Word document at the end
of a document. To insert the grid data at a specific bookmark present in the MS Word document,
call grid.SaveToDoc(FileName, BookmarkName);
Microsoft Excel files
TAdvStringGrid supports importing & exporting Microsoft Excel files in two ways. With the methods
grid.LoadFromXLS, grid.SaveToXLS, the grid imports & exports XLS files using OLE automation.
Secondly, a separate component TAdvGridExcelIO offers native import & export without requiring
that Excel is installed on the machine. It is highly recommended to use TAdvGridExcelIO as it is
significantly faster, has more features and does not require Microsoft Excel to be installed.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
17 | P a g e
Using SaveToXLS / LoadFromXLS
procedure SaveToXLS(Filename:string; CreateNewSheet: boolean = true);
procedure SaveToXLSSheet(Filename,Sheetname:string);
Using these methods, the grid contents are saved to a worksheet in the XLS file, either a default
worksheet when SaveToXLS(filename) is used, forced to a new worksheet with SaveToXLS(filename,
true) or saved to a specific named worksheet when calling SaveToXLSSheet(Filename, Sheetname);
procedure LoadFromXLS(Filename:string);
procedure LoadFromXLSSheet(Filename, SheetName:string);
LoadFromXLS loads data from the default worksheet in the grid. With LoadFromXLSSheet, data from
the named worksheet is loaded.
Using TAdvGridExcelIO
This is explained in a separate chapter: TAdvStringGrid import/export to XLS via TAdvGridExcelIO
RTF files
Via a separate component TAdvGridRTFIO, it is possible to save contents of the grid as RTF file. This
is a Microsoft Word compatible RTF file with a table that contains the grid data. Using
TAdvGridRTFIO is explained in the separate chapter: TAdvStringGrid export to RTF files via
TAdvGridRTFIO.
Advanced topics on exporting & importing
To apply transformations on cell data for loading and saving it is easy to create a descendent class
from TAdvStringGrid and override the SaveCell and LoadCell methods. In these overridden methods
a transformation such as encryption or decryption can be applied. The basic technique is:
TEncryptedGrid = class(TAdvStringGrid)
protected
function SaveCell(ACol,ARow: Integer):string; override;
procedure LoadCell(ACol,ARow: Integer; Value: string); override;
end;
function TEncryptedGrid.SaveCell(ACol,ARow: Integer): string;
begin
Result := Encrypt(GridCells[ACol,ARow]);
end;
procedure TEncryptedGrid.LoadCell(ACol,ARow: Integer; Value: string);
begin
GridCells[ACol,ARow] := Decrypt(Value);
end;
As such, when using methods like SaveToCSV, SaveToXLS, … the information will be exported in
encrypted format automatically.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
18 | P a g e
TAdvStringGrid PDF Export
The TMS Component Pack also contains a component for exporting the TAdvStringGrid content to
PDF file.
Drop a TAdvGridPDFIO component on the form and connect the TAdvStringGrid to this non-visual
component’s Grid property.
Then simply call:
AdvGridPDFIO.Save(FileName);
TAdvGridPDFIO comes with settings for header and footer as well as metadata. Header and footer
can as such be optionally generated for the PDF file independently from the TAdvStringGrid
content.
TAdvStringGrid sorting capabilities
TAdvStringGrid supports various ways to sort data inside the grid. Sorting can be triggered by a
mouse click on a column header or programmatically with various methods. The settings that
control the behaviour of sorting in the grid are grouped in the SortSettings property. In addition, the
OnGetFormat event is used to dynamically instruct the grid to the data type to use for the sort. By
default, sorting on a given column starts comparing cells for the sort for the given column but upon
finding equal cells, will use columns right from the main sort index column to do further comparing.
SortSettings
The settings that control the various sorting capabilities of TAdvStringGrid can be found under the
property SortSettings. This contains following subproperties:
AutoColumnMerge: Boolean;
When true, merged cells in multiple columns are taken
into account for sorting. Cell merging is explained in
detail later.
AutoFormat: Boolean;
When true, the grid tries to automatically guess the
format of the data in cells for the compare method
AutoSortForGrouping: Boolean
When true, the grid is automatically sorted first before
a grouping is performed. The sorting is performed on
the column for which the grouping will be applied.
BlankPos: TSortBlankPosition;
Sets the position empty cells get after sorting. This can
be either blFirst or blLast, specifying empty cells
should always come first or come last after sorting
Column: Integer;
Specifies the main sort index column
Direction: TSortDirection;
Sets the sort direction to either ascending or
descending
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
19 | P a g e
DownGlyph: TBitmap;
Specifies the glyph to use for indicating a descending
sort. If no glyph is specified a triangle is drawn.
FixedCols: Boolean;
When true, fixed columns are affected by the sort,
otherwise, fixed columns remain in the original
sequence after the sort.
Full: Boolean;
When true, all columns are taken into account for
comparing from left to right, starting from the main
sort index column
HeaderColor: TColor;
When different from clNone, the fixed column header
cell can be painted in a different color for the column
that is sorted. HeaderColor sets the top gradient start
color.
HeaderColorTo: TColor;
Idem as HeaderColor but sets the top gradient end
color.
HeaderMirrorColor: TColor;
Idem as HeaderColor but sets the bottom gradient start
color.
HeaderMirrorColorTo: TColor;
Idem as HeaderColor but sets the bottom gradient end
color.
IgnoreBlanks: Boolean;
When true, empty cells are ignored during the sort and
can be positioned in the sort either at top or at bottom
IgnoreCase: Boolean;
When true, case sensitivity is automatically ignored
when performing the sort.
IndexColor: TColor;
Sets the color of the indexed sort indicators
IndexDownGlyph: TBitmap;
Specifies the glyph to use for indicating an descending
indexed sort. If no glyph is specified a triangle is
drawn.
IndexShow: Boolean;
When true, sorting on an arbitrary column sequence is
enabled and the indexes of this sequence displayed
IndexUpGlyph: TBitmap;
Specifies the glyph to use for indicating an ascending
indexed sort. If no glyph is specified a triangle is
drawn.
InitSortDirection: TSortDirection
Specifies the initial sort direction. The initial sort
direction is the direction of the sort upon the first
column header click on an unsorted column. After the
first sort, the sort direction toggles for every click.
NormalCellsOnly: Boolean;
When true, sorting is applied to normal, i.e. non fixed
cells only.
Row: Integer;
Sets the fixed row where the sort indicator is displayed
and from where a column header click triggers the
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
20 | P a g e
sort. Maximum value for row is the number of fixed
rows in the grid.
Show: Boolean;
When true, the sort indicator is shown in the column
header cell
SingleColumn: Boolean;
When true, only a single column is sorted. All other
columns are not affected
SortOnVirtualCells: Boolean;
When true, the sorting is performed on cell text set by
OnGetDisplText instead of the internal grid data. This
is the default setting as the sort will correspond to
what can be visibly seen in the grid.
UndoSort: Boolean;
When true, a sort undo is possible. This means that
upon clicking on the header, the sorting toggles
between ascending, descending and back to unsorted.
The unsorted sequence is considered as the sequence
before the first sort was performed.
UpGlyph: TBitmap;
Specifies the glyph to use for indicating an ascending
sort. If no glyph is specified a triangle is drawn.
Specifying the dataformat with OnGetFormat
The OnGetFormat event is used to instruct the grid which compare method it should use during the
sorts for each column in the grid. By default, the grid is using an automatic format guess. This
means that the grid checks if the data in a cell is numeric, a floating point, a date, a date + time or
just alphabetic data and applies the appropriate compare methods accordingly. Although this auto
format guess can be convenient, for sorting large and complex amounts of data it is not
recommended. When mixed numeric and alphabetic data is available in a column, this auto format
guess is easily confused and the extra checks for guessing the format take extra time. With the
OnGetFormat event, the compare methods to use can be specified for each column. The event is
declared as:
TGridFormatEvent = procedure(Sender : TObject; ACol: Integer;
var AStyle:TSortStyle; var aPrefix,aSuffix:string) of object;
The TSortStyle can be:
ssAlphabetic
Use alphabetic compare
ssAlphaCase
Use case sensitive alphabetic compare
ssAlphaNoCase
Use case insensitive alphabetic compare
ssAlphaNumeric
Use combined alphabetic & numeric compare, ie. 1,5,100,A,M,K,a,r,z…
ssAlphaNumericNoCase
Use combined alphabetic & numeric compare without case sensitivity
ssAnsiAlphaCase
Use Ansi case sensitive alphabetic compare
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
21 | P a g e
ssAnsiAlphaNoCase
Use Ansi case insensitive alphabetic compare
ssAutomatic
Let grid automatically determine the format of data for comparing
ssCheckBox
Use checkbox value compare
ssCustom
Use custom compare method (explained later)
ssDate
Use date compare
ssDateTime
Use both date & time compare
ssFinancial
Use floating point with optionally thousand separator compare
ssHTML
Use HTML compare, ignoring HTML tags in text for compare
ssImages
Use image index compare
ssNumeric
Use numeric compare
ssRaw
Use raw compare method (explained later)
ssShortDateEU
Use fixed date format dd/mm/yyyy compare
ssShortDateUS
Use fixed date format mm/dd/yyyy compare
ssTime
Use time compare
ssUnicode
Use Unicode string compare (pre Delphi 2009 only)
The last parameters aPrefix and aSuffix, are use to instruct the grid to ignore fixed prefix or suffix
text for cell data for the compare. As such, the sort format can be ssNumeric while a cell contains
numeric data with some characters before or after the number as in the following example:
1234 USD
5678 USD
Setting aSuffix to ‘ USD’ will let the compare ignore this suffix and perform a compare only on
1234
5678
Example: setting sort formats with OnGetFormat
Supposing a grid contains following data:
Abc
123
1/1/1980
$ 1.025,36
Def
456
12/10/1990
$ 958,14
Ghi
789
15/4/200
$ 2.175,00
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
22 | P a g e
The OnGetFormat event is used to instruct the grid to use an alphabetic compare for the first
column, a numeric compare for the second column, a date compare (based on regional settings for
date format) for the third column and finally the fourth column to ignore the ’$ ‘ prefix and sort on
floating point data with optional thousand separator.
procedure TForm1.AdvStringGrid1GetFormat(Sender: TObject; ACol: Integer;
var AStyle: TSortStyle; var aPrefix, aSuffix: String);
begin
case ACol of
0: AStyle := ssAlphabetic;
1: AStyle := ssNumeric;
2: AStyle := ssDate;
3: begin
AStyle := ssFinancial;
APrefix := '$ ';
end;
end;
end;
Sort events
Two events are triggered when sorting is started by a click on a column header. Before the sort
starts, the OnCanSort event is triggered. By setting the parameter DoSort to false, a sort after a
column header click can be disabled. After the sort is completed, the OnClickSort event is
triggered, informing the completion of the sort for a given column. As OnCanSort is triggered before
the sort and OnClickSort after the sort, these two events are often used to specify an hourglass
cursor during lengthy sort processes:
procedure TForm1.AdvStringGrid1CanSort(Sender: TObject; ACol: Integer;
var DoSort: Boolean);
begin
Cursor := crHourGlass;
end;
procedure TForm1.AdvStringGrid1ClickSort(Sender: TObject; ACol: Integer);
begin
Cursor := crDefault;
end;
Custom sorts
Two events, OnCustomCompare and OnRawCompare are used to allow implementing custom
compare routines when the sort format style is specified as ssCustom or ssRaw. The
OnCustomCompare is triggered for each compare of two string values and expects the result to be
set through the Res parameter with values :
-1
Str1 < Str2
0
Str1 = Str2
1
Str1 > Str2
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
23 | P a g e
The OnRawCompare event is defined as:
TRawCompareEvent = procedure(Sender:TObject; ACol,Row1,Row2: Integer;
var Res: Integer) of object;
It allows comparing grid cells [ACol,ARow1] and [ACol,ARow2] in any custom way and returning the
result in the Res parameter in the same way as for the OnCustomCompare event.
Example: comparing cell objects instead of cell text with OnRawCompare
As for each cell, an object can be assigned with the grid.Objects[Col,Row]: TObject property, it is
easy to associate a number with each cell through:
Grid.Cells[Col,Row] := ‘I am text’; // cell text
Grid.Objects[Col,Row] := TObject(1234); // associated number
Through the OnRawCompare event, a sort can be done on this associated number instead of the cell
text.
procedure TForm1.AdvStringGrid1RawCompare(Sender: TObject; ACol, Row1,
Row2: Integer; var Res: Integer);
var
c1,c2: Integer;
Begin
c1 := integer(AdvStringGrid1.Objects[ACol,Row1]);
c2 := integer(AdvStringGrid1.Objects[ACol,Row2]);
if (c1 = c2) then
Res := 0
else
if (c1 > c2) then
Res := 1
else
Res := -1;
end;
Sort independent cell access
TAdvStringGrid has the capability to access cell contents with a row index irrespective of sort order.
In order to use this functionality, three methods are available:
procedure InitSortXRef;
function SortedRowIndex(Row: Integer): Integer;
function UnsortedRowIndex(Row: Integer): Integer;
The InitSortXRef method initializes the current row indexing as reference. This means that if value
“ABC” is on row 10, after sorting the grid in whatever sort sequence, you can access the cell with
contents “ABC” on reference row 10. After calling grid.InitSortXRef, sorting can be applied
programmatically or from user interface and conversion between displayed row index an reference
row index can be done by the methods: SortedRowIndex and UnsortedRowIndex.
SortedRowIndex converts the reference row index to the displayed row index.
UnsortedRowIndex converts the displayed row index to the reference row index.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
24 | P a g e
In addition, the following property also provide direct access to the reference row indexed cells:
Grid.UnSortedCells[Col,Row]: string;
Example: using SortedRowIndex and UnsortedRowIndex
// loading, initializing & sorting
Grid.SaveFixedCells := False;
Grid.LoadFromCSV(‘sample.csv’);
Grid.InitSortXRef;
Grid.SortSettings.Column := 1;
Grid.QSort;
// shows the contents of cell 1,1 before sorting
ShowMessage(Grid.UnsortedCells[1,1]);
// shows the display index for the reference row indexed cell 1,1
ShowMessage(IntToStr(Grid.SortedRowIndex(1));
Programmatic sorting control
Programmatically invoking a sort is possible with the method grid.QSort. First set the properties for
the sort through the property SortSettings and call grid.QSort. Calling grid.QSort performs the sort
on column set by grid.SortSettings.Column for all normal rows in the grid. Note there is a method
grid.SortSettings.ToggleDirection that makes it easy to automatically change the sort direction
before calling grid.QSort. In addition TAdvStringGrid also supports grouped sorting. Grouped sorting
will sort only rows that belong to the same group. It is invoked by first setting the column in
SortSettings.Column and calling grid.QSortGroup. More information on grouping can be found in the
paragraph for grouping specifically. Finally, it is also possible to programmatically undo a sort. This
is done with the method grid.QUnSort.
Programmatic control of custom sort column sequences
With TAdvStringGrid, it is possible to apply programmatic sorts in any column order. This is
achieved through the property grid.SortIndexes (which is a list of column indexes to be sorted) and
the method grid.QSortIndexed. SortIndexes is a list of column indexes. Column indexes can be
added with methods: grid.SortIndexes.Add(ColIndex: Integer) or
grid.SortIndexes.AddIndex(ColIndex: Integer; Ascending: Boolean); It is important that when
applying a new column sort order, to clear the previous list of indexes (if assigned) with
grid.SortIndexes.Clear;
Example: using QSortIndexed
Grid.SortIndexes.Clear;
// first column to sort is column 5 in ascending order
Grid.SortIndexes.AddIndex(5,true);
// second column to sort is column 2 in descending order
Grid.SortIndexes.AddIndex(2,false);
// third column to sort is column 4 in ascending order
Grid.SortIndexes.Add(4,true);
Grid.QSortIndexed;
Note: when grouping is enabled in the grid, use the methods QSortGroup and QSortGroupIndexed
which are further explained under grouping.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
25 | P a g e
Ignoring columns during sorting
By default, when grid.SortSettings.Full = true, all columns are possibly taken in account to perform
the sort, ie. when two values in a column are equal, the values in the next column are compared to
determine the order. It is possible to define one or more columns that should be ignored for
comparing during a sort. This is simply done by setting column indexes in the list
grid.IgnoreColumns.
Example:
grid.IgnoreColumns.Clear; // clear any previous set ignored columns
grid.IgnoreColumns.Add(2); // ignore column 2 during sort
grid.IgnoreColumns.Add(5); // ignore column 5 during sort
Persisting sort settings
Often it is desirable to persist the sorting a user has applied during execution of the application to
be able restore this last sort setting when the application restarts. TAdvStringGrid provides a
convenient way to handle this. The TSortSettings class features for this the methods:
TSortSettings.SaveToString: string;
TSortSettings.LoadFromString(const Value: string);
This way, when the application closes, the result of grid.SortSettings.SaveToString can stored in the
registry, an INI file, XML file or other storage and when the application starts, the last sort sequence
is restored by loading this value and applying it with:
var
s: string;
begin
s := IniFile.ReadString(‘GRID’,’SORT’,’’);
Grid.SortSettings.LoadFromString(s);
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
26 | P a g e
TAdvStringGrid inplace editing
TAdvStringGrid not only offers a huge range of built-in inplace editor types but can be extended to
use any TWinControl based component as inplace editor.
By default, when setting goEditing = true in grid.Options, the editing is enabled and the default
inplace editor is used (Note that the event OnCanEditCell can override this setting). In code,
editing can be enabled with:
Delphi:
advstringgrid1.Options := advstringgrid1.Options + [goEditing];
C++
advstringgrid1->Options << goEditing;
The normally used editor is set by grid.DefaultEditor and is by default a normal TEdit like inplace
edit with no special features. Additional inplace editors are specified through the OnGetEditorType
event. If goEditing is set true, all non fixed cells in the grid can be edited. To set some cells as
read-only in this case, the OnCanEditCell event is used. The OnCanEditCell event is triggered before
editing should start and editing can be stopped by setting the CanEdit parameter to false.
Example: setting a column to read-only
This event handler sets column 2 and 4 as read-only:
procedure TForm1.AdvStringGrid1CanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
CanEdit := not (ACol in [2,4]);
end;
Alternatively, a cell can also be set as readonly with properties. To do this, following code can be
used:
Delphi:
advstringgrid1.ReadOnly[col,row] := true;
C++
advstringgrid1->ReadOnly[col][row] = true;
Example: using the OnGetEditorType event
This event specifies which inplace editor to use for columns 1-4.
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1: AEditor := edNumeric;
2: AEditor := edComboEdit;
3: AEditor := edSpinEdit;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
27 | P a g e
4: AEditor := edRichEdit;
end;
end;
TEditorType is defined as :
TEditorType = (edNormal, edSpinEdit, edComboEdit, edComboList, edEditBtn, edMaskEditBtn,
edCheckBox, edDateEdit, edDateTimeEdit, edDateEditUpDown, edTimeEdit,edButton,
edDataCheckBox, edNumeric, edPositiveNumeric, edFloat, edCapital, edMixedCase, edPassword,
edUnitEditBtn, edLowerCase, edUpperCase, edFloatSpinEdit, edTimeSpinEdit, edDateSpinEdit,
edNumericEditBtn, edFloatEditBtn, edCustom, edRichEdit, edUniEdit, edUniEditBtn,
edUniComboEdit, edUniComboList, edUniMemo,edValidChars,edCalculatorDropDown,
edTrackBarDropDown, edColorPickerDropDown, edImagePickerDropDown, edMemoDropDown,
edDetailDropDown, edGridDropDown, edTimePickerDropDown, edControlDropDown,
edNumericUnitEditBtn, edFloatUnitEditBtn);
With:
edButton
Button
edCapital
Edit with all capitalized text only
edCheckBox
Checkbox
edComboEdit
Editable combobox
edComboList
Non-editable combobox
edCustom
Custom edit control (see advanced topics for editing)
edDataCheckBox
Checkbox with check value dependent on cell text
edDateEdit
Datepicker
edDateEditUpDown
Date edit with up/down buttons
edDateSpinEdit
Date spin edit control
edDateTimeEdit
Date + time edit
edEditBtn
Edit control with button attached
edMaskEditBtn
Edit control with mask and button attached
edFloat
Edit allowing floating point data only
edFloatEditBtn
Floating point only edit control with button attached
edFloatSpinEdit
Floating point spin edit control
edLowerCase
Edit with all lowercase entry
edMixedCase
Edit with automatic first capital letter
edNormal
Normal inplace edit
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
28 | P a g e
edNumeric
Edit allowing signed numeric data only
edNumericEditBtn
Numeric only edit control with button attached
edPassword
Edit in password style
edPositiveNumeric
Edit allowing unsigned numeric data only
edRichEdit
Rich text editor
edSpinEdit
Spin edit control
edTimeEdit
Time edit
edTimeSpinEdit
Time spin edit control
edUniComboEdit
Unicode editable combobox
edUniComboList
Unicode non editable combobox
edUniEdit
Unicode edit
edUniEditBtn
Unicode edit with button attached
edUniMemo
Unicode multiline edit
edUnitEditBtn
Edit control with unit selection and button attached
edNumericUnitEditBtn
Edit control that only allows numeric input with unit selection and
button attached
edFloatUnitEditBtn
Edit control that only allows floating point input with unit selection and
button attached
edPositiveFloat
Edit allowing positive floating point data only
edUpperCase
Edit with all uppercase entry
edValidChars
Accept only keys that are part of the value set with property
grid.ValidChars:string or also grid.ValidCharSet: TCharSet
edColorPickerDropDown
Color picker with 3 color selection methods: dropdown list of colors,
colorcube or color spectrum
edImagePickerDropDown
Image picker inplace edit control
edTimePickerDropDown
Inplace editor with watch in dropdown to select a time value
edTrackbarDropDown
Numeric only edit control with dropdown trackbar to select an integer
value
edDetailDropDown
Combobox style inplace editor where each item in the dropdown can
have an image and combination of a caption text and notes.
edGridDropDown
Edit control with grid as dropdown. Value is selected from the grid from
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
29 | P a g e
the lookup column
edMemoDropDown
Edit control with dropdown memo
edCalculatorDropDown
Edit control with dropdown calculator
edAdvGridDropDown
Edit control with TAdvStringGrid as dropdown control
Normal editor
With a normal cell edit control, any characters can be entered. If grid.MaxEditLength > 0, then the
length of the characters to enter in a cell is limited to grid.MaxEditLength. With
grid.MaxEditLength, the string length of a cell is limited only by the length of a string type. The
maximum input length can be set different from different columns using the OnGetEditorProp event
that is triggered before editing starts, ie:
procedure TForm1.AdvStringGrid1GetEditorProp(Sender: TObject; ACol,
ARow: Integer; AEditor: TEditorType);
begin
case ACol of
1: AdvStringGrid1.MaxEditLength := 8;
2: AdvStringGrid1.MaxEditLength := 16;
else
AdvStringGrid1.MaxEditLength := 0;
end;
end;
For column 1, max. length of input is 8 characters, for column 2 it is 16 characters and other
columns do not have length limitations.
Masked editors
TAdvStringGrid inherits the behaviour to be able to work with masked inplace editors from
TStringGrid. The edit mask is set through the OnGetEditMask event triggered before editing starts.
This allows to set the edit mask for a given cell through the Value parameter.
Example: setting an edit mask for time editing in column 1
procedure TForm1.AdvStringGrid1GetEditMask(Sender: TObject; ACol,
ARow: Integer; var Value: String);
begin
if (ACol = 1) then
Value := '!90:00;1;_';
end;
Spin editors
The inplace spin edit control is exposed through the property grid.SpinEdit. This allows access to
additional spin edit properties that control its behaviour. The most useful properties are:
property EditorEnabled: Boolean;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
30 | P a g e
When false, the value is only editable by using the spin up & down buttons.
property Increment: LongInt;
Sets the increment step for integer values.
property IncrementFloat: Double;
Sets the increment step for floating point values.
property MaxLength;
Sets the maximum length (in characters) of the value that can be entered.
property MaxValue: LongInt;
property MinValue: LongInt;
property MinFloatValue: Double;
property MaxFloatValue: Double;
property MinDateValue: TDateTime;
property MaxDateValue: TDateTime;
Sets the minimum & maximum values that can be entered in the various modes.
Example: setting spin editors with two different ranges in two different columns
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1:begin
AEditor := edSpinEdit;
AdvStringGrid1.SpinEdit.MinValue := 1;
AdvStringGrid1.SpinEdit.MaxValue := 100;
AdvStringGrid1.SpinEdit.Increment := 2;
end;
2:begin
AEditor := edSpinEdit;
AdvStringGrid1.SpinEdit.MinValue := 1;
AdvStringGrid1.SpinEdit.MaxValue := 1000;
AdvStringGrid1.SpinEdit.Increment := 10;
end;
end;
end;
The spin edit controls trigger following events when the up/down buttons are clicked:
OnSpinClick: TSpinClickEvent;
OnFloatSpinClick: TFloatSpinClickEvent;
OnTimeSpinClick: TDateTimeSpinClickEvent;
OnDateSpinClick: TDateTimeSpinClickEvent;
The spin click events return the current value of the spin edit control and whether the up or down
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
31 | P a g e
button was pressed.
TSpinClickEvent = procedure(Sender:TObject;ACol,ARow,
AValue: Integer; UpDown: Boolean) of object;
Note: by default, spin editor up/down buttons are visible when the inplace editor is active, ie. for
only one spin editor at a time. If it is desirable that spin editor buttons are continuously visible, this
can be enabled by setting : grid.ControlLook.SpinButtonsAlwaysVisible = true.
Combobox editors
Two types of comboboxes can be used: an editable combobox and not-editable combobox. While
the inplace combobox is exposed by grid.Combobox, additional methods are defined to control the
items displayed in the combobox dropdown list and selected item:
procedure ClearComboString;
Removes all items from the inplace combobox editor.
procedure AddComboString(const s: string);
Adds a single item to the inplace combobox editor.
procedure AddComboStringObject(const s: string; AObject: TObject);
Adds a string + object to the inplace combobox editor.
function RemoveComboString(const s: string): Boolean;
Removes a single string value from the inplace combobox editor.
function SetComboSelectionString(const s: string): Boolean;
Sets the selected item of the combobox by string value.
procedure SetComboSelection(idx: Integer);
Sets the selected item of the combobox by index.
function GetComboCount: Integer;
Returns the number of items in the combobox.
Through these methods, combobox items can be preset in different ways for different cells.
Example: presetting combobox items for different columns
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
32 | P a g e
In this example, an editable combobox is set for column1 with values Berlin,Paris,London,New York
and in the second column a non-editable combobox with countries is used. The OnGetEditorProp
event is used to set the values of the combobox while the OnGetEditorType event is used to set the
editor type itself:
procedure TForm1.gridGetEditorProp(Sender: TObject; ACol,
ARow: Integer; AEditLink: TEditLink);
begin
case ACol of
1:begin
grid.ClearComboString;
grid.AddComboString('Berlin');
grid.AddComboString('Paris');
grid.AddComboString('London');
grid.AddComboString('New York');
end;
2:begin
grid.ClearComboString;
grid.AddComboString('Germany');
grid.AddComboString('France');
grid.AddComboString('United Kingdom');
grid.AddComboString('United States');
end;
end;
end;
procedure TForm1.gridGetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1: AEditor := edComboEdit;
2: AEditor := edComboList;
end;
end;
As the grid also exposes the ComboBox inplace editor directly, an alternative approach to specify
the combobox items could be:
procedure TForm1.gridGetEditorProp(Sender: TObject; ACol,
ARow: Integer; AEditLink: TEditLink);
begin
case ACol of
1: grid.Combobox.Items.Assign(StringList1);
2: grid.Combobox.Items.Assign(StringList2);
end;
end;
procedure TForm1.gridGetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1: AEditor := edComboEdit;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
33 | P a g e
2: AEditor := edComboList;
end;
end;
with StringList1 and StringList2 two string list objects that hold the items that should be displayed
in the combobox when editing respectively column 1 and column 2.
Note that when the combobox inplace editor is displayed for the first time, its selected item is set
to the item that matches the content of the cell being edited. If the cell is empty before being
edited for the first time, the combobox editor will start with the first item in the list for the type
edComboList and it will start with an empty value for the edComboEdit type. To override this
behavior and ensure that a specific value is set by default, use the OnGetEditText event that is
triggered to query the value used by the inplace editor.
In this sample code, the OnGetEditText is used in combination with the OnGetEditorType event to
ensure that when the combobox editor is started, it is preset to value “Paris” when the cell is
empty:
procedure TForm1.gridGetEditorProp(Sender: TObject; ACol,
ARow: Integer; AEditLink: TEditLink);
begin
grid.ClearComboString;
grid.AddComboString('Berlin');
grid.AddComboString('Paris');
grid.AddComboString('London');
grid.AddComboString('New York');
end;
end;
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
AEditor := edComboEdit;
end;
procedure TForm1.AdvStringGrid1GetEditText(Sender: TObject; ACol, ARow:
Integer;
var Value: string);
begin
if Value = '' then
Value := 'Paris';
end;
Something similar can be achieved by using the grid methods SetComboSelection() or
SetComboSelectionString() to set the default selection of the combobox when inplace editing starts.
The code that can be used for this is:
procedure TForm1.gridGetEditorProp(Sender: TObject; ACol,
ARow: Integer; AEditLink: TEditLink);
begin
grid.ClearComboString;
grid.AddComboString('Berlin');
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
34 | P a g e
grid.AddComboString('Paris');
grid.AddComboString('London');
grid.AddComboString('New York');
grid.SetComboSelectionString('Paris');
end;
end;
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
AEditor := edComboEdit;
end;
The combobox triggers following events:
OnComboDropDown: TClickCellEvent;
Event triggered when the combobox dropdown is opened.
OnComboCloseUp: TClickCellEvent;
Event triggered when the combobox dropdown is closed.
OnComboChange: TComboChangeEvent;
Event triggered when combo selection changes and returning the new selection index and value.
OnComboObjectChange: TComboObjectChangeEvent;
Event triggered when combo selection changes and returning the new selection index, value and
associated object.
For a combobox, it is also possible to control the width of the dropdown list. The width can
automatically adapt to the width of the largest text in the list when
grid.Navigation.AutoComboDropSize is set to true or a custom width can be set through the
property: grid.ComboBox.DropWidth: integer;
Note that a combobox editor selects a string from the dropdown list and the selected value is stored
as a string in the grid cell. In some cases, it is desirable to get the index of the selected combobox
item. You can do this using:
index := grid.ComboBox.Items.IndexOf(grid.Cells[col,row]);
or alternatively, you can use
index := grid.ComboIndex[ACol,ARow];
Additional options with using comboboxes:
By default, comboboxes are only visible when the inplace editing has started. In some situations, it
might be helpful that the user can see through the dropdown image that a cell has a combobox.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
35 | P a g e
With TAdvStringGrid this is possible by using one property and one event handler. To enable the
display of comboboxes for any cell that has a combobox inplace editor whether the cell is in edit
mode or not, set grid.ControlLook.DropDownAlwaysVisible = true.
Fine control is also present to configure whether a combobox should immediately display its
dropdownlist when the editor is activated in a cell. This can be enabled with the property
grid.MouseActions.DirectComboDrop = true
If a cell with a combobox should automatically stop the editing after a combobox item is selected,
this can be enabled by setting grid.MouseActions.DirectComboClose = true. Otherwise, the
combobox inplace editor just remains visible after selecting an item and only disappears when a
new cell is selected.
Edit with button attached
edEditBtn, edNumericEditBtn, edFloatEditBtn are three types of inplace edit controls with a button
attached. This inplace edit control is exposed as grid.BtnEdit. Some additional properties available
this way to control the behaviour of this inplace editor are:
property EditorEnabled: Boolean;
When false, the editor value can only be programmatically changed from the OnEllipsClick event
that is triggered when the button in the edit control is clicked.
property Glyph: TBitmap;
Sets the glyph that can be used on the inplace editor button.
property ButtonCaption: string;
Sets the caption that can be used on the inplace editor button.
property ButtonWidth: integer;
Sets the width of the inplace editor button.
property RightAlign: Boolean;
When true, the inplace editor is right-aligned.
Example: different edit controls with button
In this example a left and right aligned edit with button with different button caption are used:
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1:begin
AEditor := edEditBtn;
grid.BtnEdit.RightAligned := True;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
36 | P a g e
grid.BtnEdit.EditorEnabled := False;
grid.BtnEdit.ButtonCaption := '+';
end;
2:begin
AEditor := edComboList;
grid.BtnEdit.RightAligned := False;
grid.BtnEdit.EditorEnabled := True;
grid.BtnEdit.ButtonCaption := '...';
end;
end;
end;
When the attached button is pressed, the OnEllipsClick event is triggered. To set a value from this
event, modify the parameter Value. This example uses an InputQuery call to set the value:
procedure TForm1.AdvStringGrid1EllipsClick(Sender: TObject; ACol, ARow:
Integer;
var S: string);
begin
InputQuery('Enter new value','Text',s);
end;
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
AEditor := edEditBtn;
AdvStringGrid1.BtnEdit.EditorEnabled := false;
end;
Edit with unit selection and button attached
This special inplace editor to do a split edit of a physical value and a physical unit, is based on the
fact that such a value is always written as <value><unit> and that value contains numeric data only,
while the unit is a non numeric string or symbol. So, if a cell contains some string like : 100µA the
inplace unit editor will automatically allow split editing of value 100 and unit µA.
Only two things are required to get this working. First, you need to specify the inplace editor
through the OnGetEditorType event. Secondly, all properties of this inplace editor can be accessed
through the grid.BtnUnitEdit property. This BtnUnitEdit has a stringlist property that contains all
possible units.
Example: editing currents and currencies unit edit button
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
if (aCol = 1) then
begin
grid.BtnUnitEdit.Units.Clear;
grid.BtnUnitEdit.Units.Add(‘µA’);
grid.BtnUnitEdit.Units.Add(‘mA’);
grid.BtnUnitEdit.Units.Add(‘A’);
AEditor := edUnitEditBtn;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
37 | P a g e
end;
if (aCol = 2) then
begin
grid.BtnUnitEdit.Units.Clear();
grid.BtnUnitEdit.Units.Add(‘$’);
grid.BtnUnitEdit.Units.Add(‘£’);
grid.BtnUnitEdit.Units.Add(‘EU’);
AEditor := edUnitEditBtn;
end;
end;
Date picker, time and date + time selection
edDateEdit, edDateEditUpDown and edTimeEdit invoke the standard Windows TDateTimePicker
control as inplace editor for date & time editing. This control is exposed as grid.DateTimePicker.
Through this control additional properties such as colors for the inplace datepicker can be
controlled. If a cell contains both date and time, using edDateTimeEdit allows to edit both the date
& time part in the cell with a special purpose editor that has a datepicker & time edit part.
Dropdown edit controls
For an even more rich user experience, TAdvStringGrid has a set of inplace editors for choosing
colors, images, time, edit numbers via a calculator, pick values from a combobox with detail notes
per item or pick values from a dropdown grid. This set of inplace editors shares a common
structure. The dropdown has a header and footer. Both header and footer can contain HTML
formatted informational text about the editor and can feature buttons as well. The settings for the
dropdown control header and footer are exposed via grid.ControlLook.DropDownHeader and
grid.ControlLook.DropDownFooter. Note that the dropdown header and footer are optional and can
be turned off by setting the respective Visible property to false. When the SizeGrid property is set
to true on the footer, the dropdown can be resized by dragging from the bottom-right corner. Using
the time picker, memo, trackbar and calculator dropdown is straightforward. Just like with all other
edit controls, use the OnGetEditorType event and set the editor to the correct editor type. For the
color picker and image picker, some more detailed interaction with the grid is available. By default,
the color picker will set the cell color to the color choosen and will trigger the event
OnColorSelected. If we have added a shape in the cell though, it is just the color of the shape that
the color picker will set. To demonstrate this, add following code:
procedure TForm2.AdvStringGrid1GetEditorType(Sender: TObject; ACol, ARow:
Integer; var AEditor: TEditorType);
begin
// set this editor just for cell 1,1
if (Acol = 1) and (ARow = 1) then
begin
AEditor := edColorPickerDropDown;
// select the colorcube as color selector
AdvStringGrid1.ColorPickerDropDown.ColorSelectionStyle := csColorCube;
end;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
38 | P a g e
procedure TForm2.FormCreate(Sender: TObject);
begin
AdvStringGrid1.Options := AdvStringGrid1.Options + [goEditing];
AdvStringGrid1.AddShape(1,1,csRectangle, clWhite, clBlack, haBeforeText,
vaCenter);
end;
Similar to a color picker, an image picker dropdown can also be used to edit an imagelist image set
in a cell. By default, it will just trigger the OnImageSelected event when editing is done, but when
a cell has an imagelist image, it will also automatically update this image. Again, with very little
code this can be achieved. Drop an ImageList on the form and assign it to grid.GridImages and add
the code:
procedure TForm2.AdvStringGrid1GetEditorType(Sender: TObject; ACol, ARow:
Integer; var AEditor: TEditorType);
begin
if (Acol = 1) and (ARow = 1) then
begin
AEditor := edImagePickerDropDown;
// will automatically load all images from the imagelist in the image
picker
AdvStringGrid1.ImagePickerDropDown.AddImagesFromImageList;
// forces the imagepicker to display images in 2 columns
AdvStringGrid1.ImagePickerDropDown.Columns := 2;
end;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
AdvStringGrid1.Options := AdvStringGrid1.Options + [goEditing];
AdvStringGrid1.AddDataImage(1,1,0,haBeforeText, vaCenter);
end;
The detail picker dropdown can be considered as a combobox with an optional extra image per item
and additional notes text for each item. Its use is straightforward and becomes clear with following
code:
procedure TForm2.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
AEditor := edDetailDropDown;
end;
procedure TForm2.FormCreate(Sender: TObject);
var
di: TDetailItem;
begin
AdvStringGrid1.DetailPickerDropDown.Images := ImageList1;
AdvStringGrid1.DetailPickerDropDown.ItemHeight := 40;
AdvStringGrid1.DetailPickerDropDown.Items.Clear;
di := AdvStringGrid1.DetailPickerDropDown.Items.Add;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
39 | P a g e
di.ImageIndex := 0;
di.Caption := 'Delphi';
di.Notes := 'Most productive IDE for Win32 development';
di := AdvStringGrid1.DetailPickerDropDown.Items.Add;
di.ImageIndex := 1;
di.Caption := 'Delphi Prism';
di.Notes := 'Take your Pascal skills to .NET';
di := AdvStringGrid1.DetailPickerDropDown.Items.Add;
di.ImageIndex := 2;
di.Caption := 'Delphi PHP';
di.Notes := 'RAD development for PHP';
end;
Finally it is possible to have a grid as inplace editor. The value that will be displayed in the cell is
the value from the column in the grid on the selected row that is set as lookup column with
property GridDropdown.LookupColumn. To set the properties for each column in the grid, the
grid.Columns collection is available. Via this column of type TDropDownColumn, it can be defined
whether a column contains text or an imagelist image. The items in the grid can be added via
grid.Items which is a collection of TDropDownItem objects. How everything falls into place is made
clear with the sample code to initialize a dropdown grid:
var
dc: TDropDownColumn;
di: TDropDownItem;
begin
AdvStringGrid1.GridDropDown.Images := ImageList1;
dc := AdvStringGrid1.GridDropDown.Columns.Add;
dc.Header := '';
dc.ColumnType := ctImage;
dc.Width := 30;
dc := AdvStringGrid1.GridDropDown.Columns.Add;
dc.Header := 'Brand';
dc.ColumnType := ctText;
dc := AdvStringGrid1.GridDropDown.Columns.Add;
dc.Header := 'Type';
dc.ColumnType := ctText;
di := AdvStringGrid1.GridDropDown.Items.Add;
di.ImageIndex := 0;
di.Text.Add('');
di.Text.Add('BMW');
di.Text.Add('7 series');
di := AdvStringGrid1.GridDropDown.Items.Add;
di.ImageIndex := 1;
di.Text.Add('');
di.Text.Add('Mercedes');
di.Text.Add('S class');
di := AdvStringGrid1.GridDropDown.Items.Add;
di.ImageIndex := 2;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
40 | P a g e
di.Text.Add('');
di.Text.Add('Porsche');
di.Text.Add('911');
di := AdvStringGrid1.GridDropDown.Items.Add;
di.ImageIndex := 3;
di.Text.Add('');
di.Text.Add('Audi');
di.Text.Add('A8');
AdvStringGrid1.GridDropDown.LookupColumn := 1;
end;
Edit controls with lookup and auto history
The normal inplace edit and comboboxes have the capability to do lookup on predefined values and
as such perform auto completion while typing. This feature is enabled by setting grid.Lookup to
True. The values to lookup for are set in the stringlist LookupItems. Auto completion can be case
sensitive or not and this is controlled by grid.LookupCaseSensitive. With LookupHistory set True, the
lookup item list automatically grows with items typed in the grid that are not yet in the
LookupItems list.
Example: Using lookup for inplace editors
This code initializes the built-in lookup with some predefined value:
begin
with AdvStringGrid1 do
begin
Options := Options + [goEditing];
LookupItems.Clear;
LookupItems.Add('BMW');
LookupItems.Add('Mercedes');
LookupItems.Add('Audi');
LookupItems.Add('Porsche');
LookupItems.Add('Ferrari');
Lookup := true;
end;
end;
Typing ‘M’ in a cell, results in automatic lookup to ‘Mercedes’
Direct access to inplace editors
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
41 | P a g e
All inplace editors can also be directly accessed. This allows controlling additional inplace editor
properties that might not be exposed by the grid. The inplace editors are exposed as public
properties and listed here:
Grid.NormalEdit: normal basic inplace edit control
Grid.SpinEdit: inplace spin edit control
Grid.BtnEdit: inplace edit with embedded button
Grid.BtnUnitEdit: inplace edit with embedded unit selection and button
Grid.ComboBox: inplace combobox
Grid.DateTimePicker: inplace datetimepicker
Grid.InplaceRichEdit: inplace rich editor
Grid.UniEdit: inplace Unicode editor
Grid.UniEditBtn: inplace Unicode editor with button attached
Grid.UniCombo: inplace Unicode combobox
Grid.UniMemo: inplace Unicode memo
Grid.ColorPickerDropDown: color picker inplace editor
Grid.CalculatorDropDown: calculator inplace editor
Grid.GridDropDown: grid inplace editor
Grid.DetailDropDown: detail list inplace editor
Grid.MemoDropDown: dropdown memo control inplace editor
Grid.TrackBarDropDown: trackbar dropdown inplace editor
Grid.TimePickerDropDown: time picker inplace editor
Grid.ImagePickerDropDown: image picker inplace editor
Note: the NormalEdit inplace editor is only created upon need for the first inplace edit. This means
that the property Grid.NormalEdit it is not assigned as long as no inplace editing is started.
Advanced topic: rich text inplace editor
With a minimum effort, TAdvStringGrid allows rich text inplace editing. Only 2 event handlers and
one property open the way to rich text editing in every cell or selected cells of TAdvStringGrid.
Specifying the rich text editing
As with all editor types, rich text inplace editing for a cell is set with the OnGetEditorType event.
For the cells that need to be edited with an inplace rich text editor, just specify the edRichEdit as
inplace editor :
procedure TForm1.GridGetEditorType(Sender:TObject; ACol, ARow: Integer; var
AEditor: TEditorType);
begin
AEditor := edRichEdit
end;
Rich Text formatting in inplace rich text editor
TAdvStringGrid exposes its rich text inplace editor through the property Grid.InplaceRichEdit.
Through this property the selection attributes of the inplace editor can be set just as if it was a
normal standalone richedit control. The button that sets the font bold style therefore is
implemented in the following way:
procedure TForm1.BoldBtnClick(Sender: TObject);
begin
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
42 | P a g e
if Grid.InplaceRichEdit.Visible then
if fsBold in Grid.InplaceRichEdit.SelAttributes.Style then
Grid.InplaceRichEdit.SelAttributes.Style :=
Grid.InplaceRichEdit.SelAttributes.Style - [fsBold]
else
Grid.InplaceRichEdit.SelAttributes.Style :=
Grid.InplaceRichEdit.SelAttributes.Style + [fsBold];
end;
Other settings are done in a similar way.
Updating toolbar settings from the inplace rich text editor
An event is used to let toolbar settings for selected characters in the rich text editor reflect the
current selected style such as fontstyle, fontname etc.. This event OnRichEditSelectionChange is
triggered whenever the user changes the selection in the inplace rich editor. In this event, the
toolbar button style can then set to reflect the setting of the selected text.
For example, the BoldBtn style is set in this event handler in the following way:
procedure TForm1.GridInplaceRichEditSelectionChange(Sender:TObject);
begin
BoldBtn.Down := fsBold in Grid.InplaceRichEdit.SelAttributes.Style;
end;
Special focus considerations
Normally, whenever another control gains focus, the TAdvStringGrid inplace editor is hidden and the
inplace editor text is set in the grid's cell. However, with rich text inplace editing this behaviour is
not wanted. If the inplace editor would be hidden, the selection would disappear and no longer
available to apply changes such as font changes. Therefore, for a rich text inplace editor the editor
remains visible even when another control on the form gains focus. Some controls, such as a font
selection combobox can then be used to set the selected font name. However, for other control
that perform something like a grid print or preview, the rich text inplace editor should be hidden
and the cell contents should be updated before doing the print. This can be done with the
grid.HideInplaceEdit method.
Example: changing fontname through fontname combobox:
procedure TForm1.FontNameChange(Sender:TObject);
begin
if Grid.InplaceRichEdit.Visible then
Grid.InplaceRichEdit.SelAttributes.Name :=
Fontname.Items[Fontname.ItemIndex];
end;
For the print button this is:
procedure TForm1.PrintBtnClick(Sender:TObject);
begin
grid.HideInplaceEdit;
grid.Print;
end;
Advanced topic: custom inplace editors
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
43 | P a g e
TAdvStringGrid allows using other inplace editors than those built-in. This is achieved through a
component TEditLink which takes care of the communication of your edit control and the grid. In
order to use another inplace editor, it is sufficient to write an EditLink descendant with some
methods that do the specific communication with the edit control. The only requirement is that the
edit control is descendant from TWinControl which should not be a problem since almost all are.
In depth look at the TEditLink component:
TEditLink = class(TComponent)
public
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
property EditCell:TPoint;
property Grid:TAdvStringGrid;
procedure HideEditor;
function GetCellValue:string;
procedure SetCellValue(s:string);
procedure CreateEditor(aParent:TWinControl); virtual;
procedure DestroyEditor; virtual;
procedure SetFocus(value:boolean); virtual;
procedure SetRect(r:trect); virtual;
procedure SetVisible(value:boolean); virtual;
procedure SetProperties; virtual;
function GetEditControl:TWinControl; virtual;
function GetEditorValue:string; virtual;
procedure SetEditorValue(s:string); virtual;
published
property EditStyle:TEditStyle;
property PopupWidth:integer;
property PopupHeight:integer;
property WantKeyLeftRight:boolean;
property WantKeyUpDown:boolean;
property WantKeyHomeEnd:boolean;
property WantKeyPriorNext:boolean
property WantKeyReturn:boolean;
property WantKeyEscape:boolean;
property Tag:integer;
end;
The EditLink presents a series of virtual methods, properties and helper functions that can be used
to communicate with the edit control. You can override these virtual methods where the default
behaviour of the TEditLink must be changed. Below is a discussion of each of these virtual methods :
procedure CreateEditor(aParent:TWinControl);
Override this method to create an instance of your edit control. Assign the aParent parameter to its
Parent property. In this stage, the edit control should still be invisible. It is necessary to override
this method.
procedure DestroyEditor;
Override this method to free the instance of your inplace editor after editing. It is necessary to
override this method.
procedure SetFocus(value:boolean);
Override this method only if a special action is required at the time your edit control receives or
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
44 | P a g e
looses focus. Overriding this method is normally not required.
procedure SetRect(r:trect);
With this method the coordinates and size is set for the inplace edit control to fit in the cell where
inplace editing happens. An override of this method should only be necessary when your inplace edit
control does not fit into the cell itself, like for example a combobox that drops out of the cell. In
this case, you can just set the height of the edit control in the SetRect method.
procedure SetVisible(value:boolean);
Override this method only if a special action is required at the time your edit control is made visible
or is hidden again. Overriding this method is normally not required.
procedure SetProperties(value:boolean);
Override this method if properties of the edit control must be set after it is visible. Some edit
control properties only work properly when set when the edit control is visible. In this case, the
SetProperties method is the ideal place.
function GetEditControl:TWinControl;
Override this method to return your edit control as TWinControl. Your edit control should be
descendant of TWinControl so you can cast it to a TWinControl. For example :
result:=TWinControl(myEdit); It is necessary to override this method.
function GetEditorValue:string;
Override this function to return the value of your edit control as a string to put into the cell after
editing. It is necessary to override this method.
procedure SetEditorValue(s:string);
Override this method to set the value of your edit control from the current cell value before
editing. It is necessary to override this method.
Further, there are some helper functions:
procedure HideEditor;
Hides the inplace edit control. This method should be called when your edit control looses focus. It
is typically called from your edit control OnExit event.
procedure EditKeyDown;
Default key handler for special keys that are used inside the grid, such as arrow keys, return key
etc..
function GetCellValue:string;
Retrieves the cell value of the cell being edited. Normally this is not used, but done through the
SetEditorValue method.
procedure SetCellValue(s:string);
Sets the cell value of the cell being edited. Normally this is not used, but done through the
GetEditorValue method.
The EditLink properties are:
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
45 | P a g e
property EditStyle:TEditStyle;
Determines if your edit control is esInplace or esPopup style. Specify esPopup style only for inplace
edit control that can fully overlap the grid, for example when using a TMemo that could hang out of
the grid during editing. All other edit control, including a combobox should be declared as esInplace
since their main editing part stays inside the grid's cell.
property PopupWidth:integer;
Defines the width of the overlapping edit control in esPopup style.
property PopupHeight:integer;
Defines the height of the overlapping edit control in esPopup style.
property PopupLeft: integer;
Defines the left position of the popup edit control. By default when zero this is automatically
positioned under the cell being edited.
property PopupTop: integer;
Defines the top position of the popup edit control. By default when zero this is automatically
positioned under the cell being edited.
property WantKeyXXXX:boolean;
Defines if the edit control handles the key itself or the grid's default key handler should handle the
key. For multiline inplace editors for example, it might be necessary to let your edit control handle
the return key itself instead of the grid.
property Tag:integer;
Property that can be used to further identify your EditLink descendant.
property Grid:TAdvStringGrid;
Returns the grid being edited.
property EditCell:TPoint;
Returns the coordinates of the cell being edited.
Using the TEditLink with TAdvStringGrid
After the TEditLink descendant has been written to communicate with your edit control, it is
necassary to tell TAdvStringGrid to use this EditLink component and thus also your edit control. To
achieve this, the TAdvStringGrid's EditLink property is used with the OnGetEditorType event. In the
OnGetEditorType event, the inplace editor is defined as edCustom and either globally or in this
event, the EditLink property of TAdvStringGrid can be set to your descendant TEditLink. Of course,
when the grid's EditLink property is set globally, only one custom inplace editor type can be used,
but when it is set from the OnGetEditorType event, nothing prevents you from writing multiple
TEditLink descendant components and assign them dependent on which cells you want to edit in the
grid. As such, a typical OnGetEditorType event could look like :
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; aCol,
aRow: Integer; var aEditor: TEditorType);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
46 | P a g e
begin
case acol of
2: advstringgrid1.EditLink := EditLink1;
3: advstringgrid1.EditLink := EditLink2;
4: advstringgrid1.EditLink := EditLink3;
5: advstringgrid1.EditLink := EditLink4;
6: advstringgrid1.EditLink := EditLink5;
end;
if acol in [2,3,4,5,6] then
aEditor := edCustom;
end;
Here, 5 different EditLink types have been used to use a different inplace editor for 5 different
columns. As your edit control will not have been constructed yet in the OnGetEditorType event, this
is not a good place to specify properties of your edit control dependent of the position of the edit
control in the grid. Although this is usually not necessary, it can be interesting for example to
change your edit control's color or font depending on the color or font of the cell being edited. This
can be achieved in the OnGetEditorProp event which is called after your edit control has been
constructed with help of the EditLink specified. In the example below, a TAdvEdit control is used as
inplace editor and the focus color is adapted to the banding color used in the grid:
procedure TForm1.AdvStringGrid1GetEditorProp(Sender: TObject; aCol, aRow:
Integer; aEditLink: TEditLink);
begin
if Assigned(aEditLink) then
begin
if acol = 2 then
begin
if odd(arow) then
(aEditLink.GetEditControl as TAdvEdit).FocusColor:=clInfoBk
else
(aEditLink.GetEditControl as TAdvEdit).FocusColor:=clWhite;
end;
end;
end;
Example: TEditLink to use TAdvEdit in TAdvStringGrid (minimal implementation)
type
TAdvEditEditLink = class(TEditLink)
private
FEdit:TAdvEdit;
protected
procedure EditExit(Sender:TObject);
public
procedure CreateEditor(aParent:TWinControl); override;
procedure DestroyEditor; override;
function GetEditorValue:string; override;
procedure SetEditorValue(s:string); override;
function GetEditControl:TWinControl; override;
end;
To link TAdvEdit with TAdvStringGrid, only a miminum set of TEditLink methods are used :
In the CreateEditor method, the TAdvEdit instance is created, its parent is set, the OnKeyDown
event is assigned to the default EditKeyDown handler, size is set to 0 to make sure it is always
invisible, some properties like ModifiedColor, ShowModified and BorderStyle are set. Finally, since
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
47 | P a g e
TAdvEdit should handle the the Left, Right arrow keys as well as Home & End keys, the properties
WantKeyLeftRight and WantKeyHomeEnd are set accordingly :
{ TAdvEditEditLink }
procedure TAdvEditEditLink.CreateEditor(AParent:TWinControl);
begin
FEdit := TAdvEdit.Create(Grid);
FEdit.BorderStyle := bsNone;
FEdit.OnKeydown := EditKeyDown;
FEdit.OnExit := EditExit;
FEdit.Width := 0;
FEdit.Height := 0;
FEdit.Parent := AParent;
WantKeyLeftRight := True;
WantKeyHomeEnd := True;
end;
The DestroyEditor simply frees the instance of the inplace editor:
procedure TAdvEditEditLink.DestroyEditor;
begin
if Assigned(FEdit) then
FEdit.Free;
FEdit := nil;
end;
Since the TAdvEdit component works with strings as well to edit, the GetEditorValue and
SetEditorValue methods are simply setting and getting the cell contents to and from the TAdvEdit
component's Text property:
function TAdvEditEditLink.GetEditorValue:string;
begin
Result := FEdit.Text;
end;
procedure TAdvEditEditLink.SetEditorValue(s: string);
begin
FEdit.Text := s;
end;
In order to hide the editor when it looses focus, the EditExit procedure for the OnExit event, calls
the HideEditor method :
procedure TAdvEditEditLink.EditExit(Sender: TObject);
begin
HideEditor;
end;
Finally, much of the magic behind the TEditLink works because TAdvStringGrid treats the inplace
editor as a TWinControl descendant, and therefore the grid must be able to obtain it as such with
the GetEditControl method :
function TAdvEditEditLink.GetEditControl: TWinControl;
begin
Result := FEdit;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
48 | P a g e
Making more edit control properties available at design time
This was the minimal implementation of the TEditLink that uses the TAdvEdit component with its
default properties. To make the TAdvEdit properties accessible at design time, the TAdvEdit
properties can be added to the TEditLink component and transferred from the TEditLink component
to the TAdvEdit component in the SetProperties method. In the TAdvEditEditLink component
provided this is done in following way:
TAdvEditEditLink = class(TEditLink)
public
procedure SetProperties; override;
published
property EditAlign:TEditAlign read FEditAlign write FEditAlign;
property EditColor:TColor read FEditColor write FEditColor;
property ModifiedColor:TColor read FModifiedColor write FModifiedColor;
property EditType:TAdvEditType read FEditType write FEditType;
property Prefix:string read FPrefix write FPrefix;
property ShowModified:boolean read FShowModified write FShowModified;
property Suffix:string read FSuffix write FSuffix;
property Precision:integer read FPrecision write FPrecision;
end;
The set of properties that is exposed with the TEditLink is used for TAdvEdit in the SetProperties
method :
procedure TAdvEditEditLink.SetProperties;
begin
inherited;
FEdit.Color := FEditColor;
FEdit.FocusColor := FEditColor;
FEdit.EditAlign := FEditAlign;
FEdit.ModifiedColor := FModifiedColor;
FEdit.Prefix := FPrefix;
FEdit.Suffix := FSuffix;
FEdit.ShowModified := FShowModified;
FEdit.Precision := FPrecision;
end;
Using the TFormControlEditLink class
An easier way to use a custom TWinControl descendent component as inplace editor is by using the
TFormControlEditLink class. To start using this component, drop a TFormControlEditLink on the
form and the edit control you want to use as inplace editor. Assign the control to
TFormControlEditLink.Control. Implement the grid's OnGetEditorType event as:
procedure TForm1.AdvStringGrid1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
case ACol of
1: begin
AEditor := edCustom;
AdvStringGrid1.EditLink := FormControlEditLink1;
end;
end;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
49 | P a g e
From now, starting editing in the grid will show the control as inplace editor and leaving focus hides
this inplace editor. Only thing left is to implement two events for TFormControlEditLink that will
transfer the value of the control to the grid and vice versa. In this example, this is achieved with:
procedure TForm1.FormControlEditLink1GetEditorValue(Sender: TObject;
Grid: TAdvStringGrid; var AValue: string);
begin
AValue := MyControl.Text;
end;
procedure TForm1.FormControlEditLink1SetEditorValue(Sender: TObject;
Grid: TAdvStringGrid; AValue: string);
begin
MyControl.Text := AValue;
end;
Validating editing
An important part of editing is its validation. While the grid includes many capabilies to force that
only desired values can be entered, in many cases an extra validation is required. TAdvStringGrid
triggers the event OnCellValidate when editing in a cell ends. The event can be triggered in all
cases the editing of a cell ends or only when the editing ends with the value of the cell effectively
changed. This can be choosen with the public property grid.AlwaysValidate: Boolean. By default,
grid.AlwaysValidate is set to False. Through the parameters Value: string and Valid: Boolean, it can
be returned whether the edited value is valid or not and the value can be optionally automatically
restored or auto-corrected.
In this sample, the OnCellValidate event is used to force entering a value with a length of minimum
3 characters and maximum 5 characters. When the entry is incorrect, the original cell value is
restored:
procedure TForm1.AdvStringGrid1CellValidate(Sender: TObject; ACol,
ARow: Integer; var Value: string; var Valid: Boolean);
begin
valid := (length(value) >= 3) and (length(value) <= 5);
if not valid then
Value := AdvStringGrid1.OriginalCellValue;
end;
The grid provides a mechanism to notify the user of the reason the entry is not valid by showing a
balloon.
When the Valid parameter of the OnCellValidate event is set to false the balloon will show when
grid.InvalidEntryTitle, grid.InvalidEntryText are a non empty text. Additionally, the icon can be set
via grid.InvalidEntryIcon. The OnCellValidate event handler here shows how a different balloon
invalid entry text is set when the length of the input is smaller than 3 or larger than 5:
procedure TForm2.AdvStringGrid1CellValidate(Sender: TObject; ACol,
ARow: Integer; var Value: string; var Valid: Boolean);
begin
if length(value) < 3 then
begin
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
50 | P a g e
Advstringgrid1.InvalidEntryTitle := 'Input error';
Advstringgrid1.InvalidEntryText := 'Entry not sufficiently long';
Valid := false;
end;
if length(value) > 5 then
begin
Advstringgrid1.InvalidEntryTitle := 'Input error';
Advstringgrid1.InvalidEntryText := 'Entry is too long';
Valid := false;
end;
end;
This results in:
Note 1: in order to display balloons in the grid, it is required to set grid.Balloon.Enable = true.
Note 2: when reparenting the grid, it is required to set grid.Balloon.Enable = false before changing
the parent programmatically and set grid.Balloon.Enable = true again after the new parent is set.
Further balloon settings are available under grid.Balloon and discussed in the paragraph about
adding balloons to the grid.
Programmatically controlling editing
Normally, editing is started by clicking on a selected cell or pressing F2. It is also possible to start
the inplace editor by code. To do this following functions are available:
Grid.ShowInplaceEdit;
Starts the inplace editor at the currently selected cell
Grid.HideInplaceEdit;
Stops inplace editing. If the inplace editing is aleady stopped, calling this method cannot harm.
Grid.EditCell(Col,Row: integer);
Start the inplace editor on cell Col,Row
Grid.FocusCell(Col,Row: integer);
Just set the focused cell to Col,Row but do not start inplace editing.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
51 | P a g e
TAdvStringGrid mouse and navigation control
Extensive control is available for controlling navigation with keyboard and mouse in the grid and
control of automatic key triggered actions such as clipboard handling. These settings are available
through the grid.Navigation and grid.MouseActions properties.
Navigation properties
AdvanceAuto: Boolean;
When true, editing with masked inplace edit
automatically advances to the next cell when the
mask has been completed.
AdvanceAutoEdit: Boolean;
When true, after pressing return to advance the
inplace editor to the next cell, this cell is
automatically put into editing mode.
AdvanceDirection: TAdvanceDirection;
Sets the directorion of the auto advance upon
pressing Enter or Return to following values:
adTopBottom: move from top row to bottom row
and then move to next column.
adTopBottomInCol: move from top row to bottom
row and then move to top row again in same
column.
adLeftRight: move from left to right and then
move to next row.
adLeftRightInRow: move from left to right and
then move to back to first cell in same row.
AdvanceInsert: Boolean;
When true, pressing enter on the last cell of the
last row automatically inserts a new row or a new
column (depending on AdvanceDirection). When a
new row is inserted, the OnCanAddRow event is
triggered first followed by the event
OnAutoInsertRow. When a new column is inserted,
the OnCanAddCol event is triggered followed by
OnAutoInsertCol.
AdvanceOnEnter: Boolean;
When true, pressing Return or Enter automatically
advances to the next cell. The direction of the
auto advance is controlled by the
AdvanceDirection property
AdvanceOnEnterLoop: Boolean;
When true, the grid will automatically advance
back to the first (top/left) normal cell of the grid
when Enter is pressed on the last (bottom/right)
cell.
AdvanceSkipReadOnlyCells: Boolean;
When AdvanceEnter = true and the Enter key is
pressed, by default readonly cells are skipped and
the next editable cell is focused and set in edit
mode. When AdvanceSkipReadOnlyCells is false,
when the next logical cell is readonly, focus just
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
52 | P a g e
moves to the readonly cell.
AllowClipboardAlways: Boolean;
Allows clipboard actions irrespective of cells being
read-only
AllowClipboardColGrow: Boolean;
When true, the number of columns in the grid can
grow if more columns are pasted than already
present in the grid
AllowClipboardRowGrow: Boolean;
When true, the number of rows in the grid can
grow if more rows are pasted than already
present in the grid
AllowClipboardShortCuts: Boolean;
When true, pressingCtrl-Ins, Shift-Ins, Shift-Del,
Ctrl-X, Ctrl-V, Ctrl-C automatically triggers the
clipboard handling. Unless AllowClipboardAlways
is set true, clipboard actions are only applied on
editable cells.
AllowCtrlEnter: Boolean;
When true, pressing Ctrl-Enter will add a line
break in an inplace editor.
AllowDeleteRow: Boolean;
When true, pressing the Del key removes a row.
The OnAutoDeleteRow event is triggered.
AllowFmtClipboard: Boolean;
Allows copy and paste of both cell text and cell
properties in TAdvStringGrid or between multiple
TAdvStringGrid controls.
AllowInsertRow: Boolean;
When true, pressing the Ins key inserts a new row.
The OnAutoInsertRow event is triggered. The
position of the inserted row is controlled by the
InsertPosition property.
AllowRTFClipboard: Boolean;
Allows copy and paste of rich text in the grid
AllowSmartClipboard: Boolean;
When true, pasting automatically completes
ranges in selected cells. If for example 2 cells are
copied on the clipboard with values ‘1’ and ‘2’,
pasting this in 10 cells will paste as
‘1’,’2’,’3’…’10’
AlwaysEdit: Boolean;
When true, the inplace editor is always visible.
When this behaviour is wanted, this needs to be
set true instead of the TStringGrid
goAlwaysShowEditor in grid.Options
AppendOnArrowDown: Boolean;
When true, pressing the down arrow on the last
row of the grid will automatically insert a new
row.
AutoComboDropSize: Boolean;
When true, the combobox dropdown size
automatically adapts to the largest string in the
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
53 | P a g e
combobox
AutoComboSelect: Boolean;
Determines whether the combobox used as
inplace editor for a cell is shown with the cell
value immediately as selected item in the
dropdown or not.
AutoGotoIncremental: Boolean;
Can be used combined with AutoGotoWhenSorted
where the lookup for text is incremental, i.e. the
search refines with each character typed.
AutoGotoWhenSorted: Boolean;
When true, typing a character automatically
moves the current cell to the first cell that starts
with character typed. This applies for pressing
characters in sorted columns only.
ClipboardCutAction: TClipboardCutAction;
Value can be set to caClear to just clear the cells
where a cut is performed or caRemove to remove
rows completely from the grid (in case row
selection is enabled).
ClipboardPasteAction: TClipboardPasteAction;
Value can be set to paReplace or paInsert. When
ClipboardPasteAction is paReplace, cells are
replaced from the top left corner with pasted cell
values. When ClipboardPasteAction is paInsert,
cells are inserted in the grid from the top, left
selected cell.
CopyHTMLTagsToClipboard: Boolean;
When true, HTML tags are also copied on the
clipboard
CursorAdvance: TCursorAdvance;
This can be any of the following 3 values:
caDefault, caSnaak, caLoop.
caDefault: This is the default setting, this means
that when the arrow keys are pressed and the
first/last row/column of the grid is reached,
navigation stops.
caLoop: This means that when the arrow key is
pressed on first/last cells of a column/row, the
active cells moves to the last/first cell of this
column/row.
caSnake: This means that when the arrow key is
pressed on first/last cells of a column/row, the
active cells moves to the last/first cell of the next
column/row.
CursorMoveRows: Boolean;
When true, pressing Ctrl and arrow up or down
moves the selected row or rows up or down.
CursorWalkAlwaysEdit: Boolean;
Controls whether the inplace editor of the next
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
54 | P a g e
cell after pressing left / right is automatically put
in edit mode or not
CursorWalkEditor: Boolean;
When true, pressing cursor left key if caret is on
first character position moves to previous cell,
pressing cursor right key when caret is on last
character position moves to the next cell
EditSelectAll: Boolean;
When true, all text is selected when the inplace
editor starts. Otherwise, no text is selected and
the caret is after the last character position.
HomeEndKey: THomeEndAction;
Defines the behaviour of Home and End key as
either going to top/bottom row or left rightmost
column
ImproveMaskSel: Boolean;
Automatically positions entry on first editable
character of the mask edit instead of selecting
the full mask
InsertPosition: TInsertPosition;
Determines if a row is inserted before or after the
current row when Ins is pressed and
AllowInsertRow is True
KeepHorizScroll: Boolean;
When true, navigating up or down in the grid with
a horizontally scrolled grid keeps this horizontal
scroll instead of scrolling back to leftmost position
KeepScrollOnSort: Boolean;
When true, the horizontal scroll position is not
changed when the grid is sorted by clicking on a
column header. When false, the horizontal scroll
position is reset to the leftmost position.
LeftRightRowSelect: Boolean;
When true, the default behaviour applies and if
row selection is enabled, pressing left/right arrow
keys change the selected row. When false,
left/right arrow keys change the horizontal scroll
LineFeedOnEnter: Boolean;
When true, pressing Ctrl-Enter adds a linefeed in
the cell instead of stopping the inplace edit
MoveRowOnSort: Boolean;
When true, the current selected row remains in
focus after sort
MoveScrollOnly: Boolean;
When true, only the scroll position in the grid
changes when pressing keys
Up,Down,Next,Prior,Home,End. When false, it is
the selection that changes in the grid for these
keys.
SkipFixedCells: Boolean;
When true, using the arrow keys to move the
selected cell will let the selection jump over fixed
(non-selectable) cells in the grid.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
55 | P a g e
TabAdvanceDirection: TAdvanceDirection;
Sets the directorion of the auto advance upon
pressing Tab to either adTopLeft or adLeftRight.
Note that goTabs must be set true in grid.Options
to allow tab keys in the grid.
TabToNextAtEnd: Boolean;
When true and goTabs is set True in grid.Options,
after tabbing inside the grid to the last cell, the
focus moves to the next control
MouseActions properties
AllColumnSize: Boolean;
When true, resizing one column resizes all columns
proportionally. Note that goColSizing needs to be set
to True in grid.Options for this
AllRowSize: Boolean;
When true, resizing one row resizes all rows
proportionally. Note that goRowSizing needs to be
set to True in grid.Options for this
AllSelect: Boolean;
When true, all cells can be selected by clicking in
the topleft fixed cell
AutoFocus: Boolean;
When true, the grid automatically gains focus when
the mouse hovers the grid
AutoSizeColOnDblClick: Boolean;
When true, a double click on the column edge will
autosize the column to the text width.
CaretPositioning: Boolean;
When true, clicking a cell to start inplace editing
automatically positions the caret on the position
where the mouse click happened to start editing
CheckAllCheck: Boolean;
When true, a checkbox click in the top fixed row will
automatically set all checkboxes in the column
below to the same setting as the top checkbox.
ColSelect: Boolean;
When true, a full column can be selected by clicking
a column header cell
DirectComboClose: Boolean;
When true, the combobox inplace editing
automatically ends when its dropdown is closed.
DirectComboDrop: Boolean;
When true, clicking on a cell with combobox inplace
editor immediately causes a dropdown of the
combobox
DirectDateClose: Boolean;
When true, the datepicker inplace editing
automatically ends when its dropdown calendar is
closed.
DirectDateDrop: Boolean;
When true, clicking on a cell with datepicker inplace
editor immediately causes a dropdown of the
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
56 | P a g e
calendar.
DirectEdit: Boolean;
When true, clicking a cell immediately starts editing
instead of first selecting the cell and entering edit
mode after another mouse click.
DisjunctCellSelect: Boolean;
When true, allows selection of disjunct cells through
Ctrl + left mouse click. The list of disjunct selected
cells can be obtained with the SelectedCell[Index:
Integer]: TGridCoord property where
SelectedCellCount is returning the number of
selected cells.
DisjunctColSelect: Boolean;
When true, allows selection of disjunct columns
through Ctrl + left mouse click. The selectionstate of
columns can be obtained through
grid.ColSelect[ARow: Integer]: Boolean
DisjunctRowSelect: Boolean;
When true, allows selection of disjunct rows through
Ctrl + left mouse click. The selectionstate of rows
can be obtained through grid.RowSelect[ARow:
Integer]: Boolean
DisjunctRowSelectNoCtrl: Boolean;
When true and combined with DisjunctRowSelect =
true, disjunct row selection is possible without
keeping the Ctrl key down.
EditOnDblClickOnly: Boolean;
When true, the inplace editing is only started when
double clicking on a cell. Otherwise, the editing is
started by default upon a single click in a selected
cell.
FixedColsEdit: TGridFixedCellEdit;
Selects the type of action needed to start the editor
for the fixed column
FixedColsEditor: TGridFixedCellEditor;
Sets the type of fixed cell editor: a normal editor,
editable combobox or combobox list
FixedRowsEdit: TGridFixedCellEdit;
Selects the type of action needed to start the editor
for the fixed row
FixedRowsEditor: TGridFixedCellEditor;
Sets the type of fixed cell editor: a normal editor,
editable combobox or combobox list
HotmailRowSelect: Boolean;
When true, row selection can be done through clicks
on the checkbox in the first fixed column.
MoveRowOnNodeClick: Boolean;
When true, clicking on a node also moves the
selected cell or row to the row where the node is
positioned.
NoAutoRangeScroll: Boolean;
When true, scrolling range selection is not
automatically started when clicking a half visible
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
57 | P a g e
cell at bottom or right side of the grid
NodeAllExpandContract: Boolean;
When true, a node in the top fixed row will expand
or collaps all nodes in the column below the fixed
cell.
NoScrollOnPartialCol: Boolean;
When true, the grid is not automatically scroll to
bring a partially visible column in view that is
clicked.
NoScrollOnPartialRow: Boolean;
When true, the grid is not automatically scroll to
bring a partially visible row in view that is clicked.
PartialScrollDelta: Integer;
Sets the nr. of rows / columns to scroll when the
user clicks on a partially visible column or row.
PreciseCheckBoxCheck: Boolean;
When true, a checkbox will only toggle when the
mouse is over the checkbox, otherwise the checkbox
will toggle for a click anywhere in the cell.
RangeSelectAndEdit: Boolean;
When true, range selection and editing style
(goRangeSelect and goEditing in grid.Options) can be
combined
RowSelect: Boolean;
When true, a full row can be selected by clicking a
row header cell
RowSelectPersistent: Boolean;
When true, in a grid with disjunct selected rows
with nodes, the selection of rows is persisted when
nodes collaps or expand.
SelectOnRightClick: Boolean;
When true, the mouse right-click button operates
just like the left button to select a cell
SizeFixedCol: Boolean;
Allows sizing with mouse of the first fixed column(s)
which otherwise cannot be sized when goColSizing is
True in grid.Options
SizeFixedRow: Boolean;
Allows sizing with mouse of the first fixed row(s)
which otherwise cannot be sized when goRowSizing
is True in grid.Options
ToggleNodeOnDblClick: Boolean;
When true, a double click on cells in a row that has
a node will open / close the node.
TouchScroll: Boolean;
When true, scrolling can be done by touch and drag
and inertia scrolling will be performed upon
mouse/touch release
WheelAction: TWheelAction
Selects whether a mouse wheel move will scroll the
grid or move the selection in the grid.
WheelActive: TWheelActive
Sets whether the mouse wheel affects grid scrolling
when the grid has focus (waFocus) or only when the
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
58 | P a g e
mouse is over the grid when it has focus
(waMouseOver).
WheelIncrement: integer
Selects the number of rows to move for a mouse
wheel movement. When zero, the default number as
configured in Windows is used.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
59 | P a g e
TAdvStringGrid column sizing
When goColSizing is set to true in grid.Options, the columns can be resized by dragging the
separators between column header cells. The column size can be programmatically set & retrieved
via grid.ColWidths[ColumnIndex]: integer;
Various other options exist that relate to column size and control its behavior. Options are grouped
under grid.ColumnSize class property:
grid.ColumnSize.Key: string;
Sets either the registry key or the INI file name where
column widths can be persisted.
grid.ColumnSize.Location:
TColumnSizeLocation;
Specifies whether column sizes will be persisted in the
registry or an INI file.
grid.ColumnSize.Rows: TAutoSizeRows;
Specifies what rows of a column to take in account for
auto column size calculation. This can be all rows
(arAll: i.e. normal rows + fixed rows), only normal rows
(arNormal) or only fixed rows (arFixed).
grid.ColumnSize.Save
When true, column widths are automatically persisted
in either the INI file or the registry.
grid.ColumnSize.Section:
Specifies the INI file section or registry node name
where values are persisted
grid.ColumnSize.Stretch:
When true, the width of one or more columns is
automatically adapted to fill the entire grid client
rectangle. When the total column widths already
exceed the client width, nothing will change. By
default, grid.ColumnSize.StretchColumn = -1 and this
means that the rightmost column will be the column
that is stretched.
grid.ColumnSize.StretchAll:
When true, all columns are stretched to fill the grid
client width in an equidistant way
grid.ColumnSize.StretchColumn:
Sets the index of the column to be stretched. By
default this is -1 to let the rightmost column stretch.
grid.ColumnSize.SynchWithGrid:
When true, the columns are proportionally sized with
the grid when the grid’s client width changes.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
60 | P a g e
TAdvStringGrid styles
The grid has various built-in options to define its style. There is a design-time gallery of styles that
is available from the design-time context menu:
From here, a wide range of Office, Windows and custom styles are available. Styles can also be set
at runtime. The TAdvStringGrid is compliant to the TMS styles interface. This means that with a
TAdvFormStyler on the form, setting the style on this component will automatically change the style
of all TMS components on the form that are TMS style interface compliant and thus also
TAdvStringGrid. This means that with a single property, all TMS components on the form can adapt
to the same consistent style. (TAdvFormStyler/TAdvAppStyler are part of the TMS Component Pack:
http://www.tmssoftware.com/site/tmspack.asp and the style mechanism is explained at
http://www.tmssoftware.com/site/atbdev3.asp) Also without this TAdvFormStyler, it is easy to
programmatically set the style for TAdvStringGrid. Add the unit AdvStyleIF to the uses list and the
style can be set via:
grid.SetComponentStyle(AStyle: TTMSStyle);
TTMSStyle is defined as:
// color schemes consistent with Office 2003
tsOffice2003Blue,
tsOffice2003Silver,
tsOffice2003Olive,
tsOffice2003Classic,
// color schemes consistent with Office 2007
tsOffice2007Luna,
tsOffice2007Obsidian,
tsOffice2007Silver,
// color schemes consistent with Office 2010
tsOffice2010Blue,
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
61 | P a g e
tsOffice2010Silver,
tsOffice2010Black,
// color schemes consistent with Office 2013
tsOffice2013White,
tsOffice2013LightGray,
tsOffice2013Gray,
// color schemes consistent with Windows editions
tsWindowsXP,
tsWindowsVista,
tsWindows7,
tsWindows8,
// color scheme without gradients for use on terminals
tsTerminal,
// custom color scheme
tsCustom
Note that a custom color scheme means that the style will not affect color settings of the grid, i.e.
the grid will keep its colors as defined at design-time or as configured programmatically at run-
time.
It is possible to make custom extensions for the grid gallery or load & save styles at run-time. To do
this, the functions
Grid.SaveVisualProps(FileName: string);
Grid.LoadVisualProps(FileName: string);
can be used.
To add a new style for the TAdvStringGrid style gallery, set colors of the grid and call
grid.SaveVisualProps(FileName) and choose a filename with extension .GP. Put this file in the \My
Documents folder and the grid will recognize and use this file for the gallery. The .GP files provided
with TAdvStringGrid can also be deployed and loaded at runtime via
grid.LoadVisualProps(FileName);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
62 | P a g e
TAdvStringGrid cell and cell properties access
Various properties enable handling cell data. The most simple way is to use the
grid.Cells[ACol,ARow]: string property. In addition TAdvStringGrid provides:
grid.AllCells[ACol,ARow]: string;
Access the grid cell as string irrespective of hidden
columns or rows. grid.AllCells returns the cell as
displayed, ie. after possible processing of the real cell
text by the event OnGetDisplText
grid.AllFloats[ACol,ARow]: Double;
Access the grid cell as float irrespective of hidden
columns or rows
grid.AllGridCells[ACol,ARow]: string;
Access the grid cell as string irrespective of hidden
columns or rows. grid.AllGridCells returns the cell as
stored, ie. before possible processing by the event
OnGetDisplText
grid.AllObjects[ACol,ARow]: TObject;
Access the TObject that can be associated with each
cell irrespective of hidden columns or rows
grid.AllWideCells[ACol,ARow]: widestring
Access the grid cell as widestring irrespective of
hidden columns or rows
grid.Dates[ACol,ARow]: TDateTime;
Access the grid cell as date
grid.Floats[ACol,ARow]: Double;
Access the grid cell as double. If no floating point data
is in the cell, the value 0.0 is returned. When setting
the cell data through grid.Floats, the grid.FloatFormat
property is used to format the floating point data as
text.
grid.GridCells[ACol,ARow]: string;
Access the grid cell as string. grid.GridCells returns the
cell as stored, ie. before possible processing by the
event OnGetDisplText
grid.Ints[ACol,ARow]: Integer;
Access the grid cell as integer. If no integer is in the
cell, the value 0 is returned.
grid.Objects[ACol,ARow]: TObject;
Access the TObject that can be associated with each
cell
grid.Times[ACol,ARow]: TDateTime;
Access the grid cell as time
grid.WideCells[ACol,ARow]: widestring
Access the grid cell as widestring
grid.OriginalCells[ACol,ARow]: string
Provides access to cells irrespective of column
ordering. The cells can be accessed with the original
column index before a user started to move columns
(when goColMoving is true in grid.Options)
grid.StrippedCells[ACol,ARow]: string
Read-only property returning the plain text of a grid
well with all possible HTMLformatting tags or RTF
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
63 | P a g e
formatting removed
grid.GetSelectionAsText: string
Returns all text in one or multiple selected cells as
text. The text format is compatible with how Excel
puts multiple cell content on the clipboard.
Grid.SetSelectionAsText(Value:string)
Sets the contents of the selected cells with text that is
formatted in the same way that Excel formats multiple
cell text on the clipboard.
Two ways exist to apply colors, fonts & alignment to grid cells. A dynamic way exists that allows
setting these properties through events. The dynamic cell settings through events is a flexible and
memory friendly way to apply colors, alignment etc.. to grid cells as no additional storage is
required per cell for storing these cell properties.
Dynamic cell properties
The events to handle these settings are:
OnGetCellColor:
TGridColorEvent = procedure(Sender: TObject; ARow, ACol: Integer;
AState: TGridDrawState; ABrush: TBrush; AFont: TFont ) of object;
This event is triggered when painting a cell and queries for the background brush of the cell and the
font.
OnGetAlignment:
TGridAlignEvent = procedure (Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment;var VAlign: TAsgVAlignment) of object;
The grid align event is also triggered when painting a cell and queries for horizontal and vertical
text alignment in a cell. Note that the default grid alignment is set via the property
grid.DefaultAlignment. When grid.AutoNumAlign is set to true, the grid will automatically right-
justify cells that contain numbers.
OnGetCellGradient:
TGridGradientEvent = procedure(Sender: TObject; ARow, ACol: Integer;
var Color, ColorTo, ColorMirror, ColorMirrorTo: TColor) of object;
This event is triggered to dynamically set a dual (mirrored) gradient. The upper half rectangular
gradient is from Color to ColorTo, the bottom half rectangular gradient is from ColorMirror to
ColorMirrorTo.
Example: setting font color and alignment depending on cell values
procedure TForm1.AdvStringGrid1GetCellColor(Sender: TObject; ARow,
ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
64 | P a g e
begin
if grid.Ints[ACol,ARow] > 0 then
AFont.Color := clBlack
else
AFont.Color := clRed;
end;
procedure TForm1.AdvStringGrid1GetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
if (grid.Ints[ACol,ARow] >= 1000) then
HAlign := taRightJustify
else
HAlign := taLeftJustify;
end;
Static cell properties
Cell properties can also be set directly. Using this approach of course requires more memory as the
properties are stored with each cell. Possible properties are:
property Alignments[Col,Row: Integer]: TAlignment;
property Colors[Col,Row: Integer]: TColor;
property ColorsTo[Col,Row: Integer]: TColor;
property FontColors[Col,Row: Integer]: TColor;
property FontStyles[Col,Row: Integer]: TFontStyles;
property FontSizes[Col,Row: Integer]: Integer;
property FontNames[Col,Row: Integer]: string;
Example: setting a cell 2,3 to red background, bold Tahoma font and right aligned
Grid.Colors[2,3] := clRed;
Grid.FontStyles[2,3] := Grid.FontStyles[2,3] + [fsBold];
Grid.FontNames[2,3] := ‘Tahoma’;
Grid.Alignments[2,3] := taRightJustify;
Note: the property grid.ColorsTo[Col,Row: Integer]: TColor is used for specifying vertical gradients
in cells from color set by Colors[] to color set by ColorsTo[].
This sets a vertical gradient from red to white in cell 1,1:
Grid.Colors[1,1] := clRed;
Grid.ColorsTo[1,1] := clWhite;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
65 | P a g e
TAdvStringGrid row & column methods
TAdvStringGrid provides several methods to access, insert, remove, move, swap rows and columns.
Grid.InsertRows(RowIndex, RCount: integer);
Inserts RCount rows in the grid at position RowIndex
Grid.RemoveRows(RowIndex, RCount: integer);
Deletes RCount rows in the grid at position RowIndex
Grid.MoveRow(FromIndex, ToIndex: integer);
Moves one row at position FromIndex to the new positon ToIndex
Grid.MoveRows(FromIndex, ToIndex, RCount: integer);
Moves RCount rows starting from index FromIndex to ToIndex
Grid.SwapRows(Row1, Row2: integer);
Swaps rows Row1 and Row2
Grid.AddRow;
Adds one row to the grid
Grid.InsertCols(ColIndex, CCount: integer);
Inserts CCount rows in the grid at position ColIndex
Grid.RemoveCols(ColIndex, CCount: integer);
Deletes CCount columns in the grid at position ColIndex
Grid.MoveColumn(FromIndex, ToIndex: integer);
Moves one column at positon FromIndex to the new position ToIndex
Grid.SwapColumns(Col1, Col2: integer);
Swaps columns Col1 and Col2
Grid.DistinctValues(Col: integer): TStrings;
Returns a stringlist of distinct values in column Col.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
66 | P a g e
TAdvStringGrid cell graphics
TAdvStringGrid has support to add all kinds of graphics to a cell. These include:
Bitmap Windows bitmap
Icon Windows icon
ImageList Imagelist element
DataImage Cell data dependent imagelist element
Images Multiple imagelist elements
Picture Picture
FilePicture Picture file reference
Rotated Rotated text
Comment Comment indicator
CheckBox Checkbox
DataCheckBox Cell data dependent checkbox
Radiogroup Radiobuttons
Radiobutton Radiobutton
XP Progress XP style Progressbar
Progress Progressbar
ProgressPie Progress pie
RangeIndicator Bi-color range indicator
Button Button
BitButton BitButton
Balloon Balloon
Shapes Series of graphic shapes
Rating Rating control
Interface Custom graphics via interface
Bitmaps
The functions available to handle bitmaps in cells are:
function CreateBitmap(ACol,ARow: Integer;transparent: Boolean;
hal:TCellHalign; val:TCellValign):TBitmap;
procedure AddBitmap(ACol,ARow: Integer;ABmp:TBitmap;Transparent: Boolean;
hal:TCellHalign; val:TCellValign);
procedure RemoveBitmap(ACol,ARow: Integer);
function HasBitmap(ACol,ARow: Integer): Boolean;
function GetBitmap(ACol,ARow: Integer): TBitmap;
The difference between CreateBitmap and AddBitmap is that with CreateBitmap, the bitmap
instance is created, maintained and destroyed by the grid while with AddBitmap it is the
responsibility of the programmer to create the instance and destroy it.
In code this difference becomes clear:
// add bitmap from resource to the grid
Grid.CreateBitmap(2,3,True,haBeforeText,vaTop).LoadFromResourceName(HInstan
ce,’TEST’);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
67 | P a g e
var
Bmp: TBitmap;
Bmp := TBitmap.Create;
Bmp.LoadFromResourceName(HInstance,’TEST’);
Grid.AddBitmap(2,3,True,haBeforeText,vaTop);
// at the end of the application, the bitmap needs to be destroyed
Bmp.Free;
Icons
The functions available to handle icons in cells are:
function CreateIcon(ACol,ARow: Integer; hal:TCellHalign;
val:TCellValign):TIcon;
procedure AddIcon(ACol,ARow: Integer;AIcon:TIcon; hal:TCellHalign;
val:TCellValign);
procedure RemoveIcon(ACol,ARow: Integer);
The same logic applies for Icons as for Bitmaps for the difference between CreateIcon and AddIcon.
Imagelist elements
An image from the imagelist assigned the the grid.GridImages property can be inserted in a cell.
The following methods are available for this:
procedure AddImageIdx(ACol,ARow,Aidx:
Integer;hal:TCellHalign;val:TCellValign);
procedure RemoveImageIdx(ACol,ARow: Integer);
function GetImageIdx(ACol,ARow: Integer;var idx: Integer): Boolean;
The Idx parameter is the index of the image in the imagelist. The GetImageIdx returns false if
GetImageIdx was called for a cell that does not contain an imagelist element.
It is also possible to add an imagelist element with an index that is set through the cell text with
these methods:
procedure AddDataImage(ACol,ARow,Aidx: Integer; hal:TCellHalign;
val:TCellValign);
procedure RemoveDataImage(ACol,ARow: Integer);
function HasDataImage(ACol,ARow: Integer): Boolean;
To set image 2 from the imagelist in a cell 2,3, this requires:
Grid.AddDataImage(2,3,2,haBeforeText,vaTop);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
68 | P a g e
This sets the cell text to ‘2’. If later the cell text is changed to ‘3’, the image will automatically
change to image 3 of the imagelist.
Multiple imagelist elements
To add multiple images in a cell, two methods are defined:
procedure AddMultiImage(ACol,ARow,Dir: Integer; hal:TCellHalign;
val:TCellValign);
procedure RemoveMultiImage(ACol,ARow: Integer);
The Dir parameter sets the direction of the images, with 0 = horizontal and 1 = vertical.
After calling AddMultiImage, the indexes of the images can be set with the property
Grid.CellImages[ACol,ARow]: TIntList;
Example: setting 3 imagelist based images in a cell
Grid.AddMultiImage(2,3,0,haBeforeText,vaTop);
Grid.CellImages[2,3].Add(2); // index of first image
Grid.CellImages[2,3].Add(0); // index of second image
Grid.CellImages[2,3].Add(5); // index of third image
Pictures
Adding pictures is very similar to adding bitmaps to a cell. The CreatePicture and AddPicture are
available to add a picture that is either created, maintained and destroyed by the grid or a picture
that is created, maintained and destroyed by the application. An extra parameter for adding
pictures is the stretch mode. This controls how the picture is stretched in the cell and can be:
TStretchMode =
(noStretch,Stretch,StretchWithAspectRatio,Shrink,ShrinkWithAspectRatio);
noStretch
the picture is not stretched
Stretch
stretch horizontally & vertically to fit in the cell
StretchWithAspectRatio
stretch horizontally & vertically with aspect ratio to fit in the cell
Shrink
only shrink the image when it is too large for the cell
ShrinkWithAspectRatio
shrink with aspect ratio when image is too large
function CreatePicture(ACol,ARow:Integer; transparent:Boolean;
stretchmode:TStretchMode; padding:Integer; hal:TCellHalign;
val:TCellValign):TPicture;
procedure AddPicture(ACol,ARow: Integer;APicture:TPicture;transparent:
Boolean; stretchmode:TStretchMode; padding: Integer; hal:TCellHalign;
val:TCellValign);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
69 | P a g e
procedure RemovePicture(ACol,ARow: Integer);
function HasPicture(ACol,ARow: Integer): Boolean;
function GetPicture(ACol,ARow: Integer): TPicture;
With normal pictures, once the pictures are created or added, the picture requires memory
necessary for holding the picture. When holding a large amount of large pictures, this can quickly
become a problem. Therefore, a TFilePicture can be created and inserted. A TFilePicture only
contains a reference to the file picture and does not require memory to hold the picture. The
TFilePicture will load and display the picture only for the visible cells.
function CreateFilePicture(ACol,ARow: Integer;Transparent: Boolean;
StretchMode:TStretchMode; padding:Integer; hal:TCellHalign;
val:TCellValign): TFilePicture;
procedure AddFilePicture(ACol,ARow:
Integer;AFilePicture:TFilePicture;Transparent:
Boolean;stretchmode:TStretchMode;padding:
Integer;hal:TCellHalign;val:TCellValign);
procedure RemoveFilePicture(ACol,ARow: Integer);
function GetFilePicture(ACol,ARow: Integer): TFilePicture;
Example: adding a picture with normal picture methods and file picture methods
Grid.CreatePicture(2,3,True,Shrink,0,haLeft,vaTop).LoadFromFile(‘TST.JPG’);
Grid.CreateFilePicture(2,3,True,Shrink,0,haLeft,vaTop).Filename :=
‘TST.JPG’;
Rotated text
Text rotated in any angle can be added in a cell. Note that it is required that font used for the cell
is a TrueType font. Non truetype fonts are not guaranteed to work with text rotation. Following
methods are available to help with handling rotated text in cells:
procedure AddRotated(ACol,ARow: Integer; AAngle: Smallint; s: string);
procedure SetRotated(ACol,ARow: Integer; AAngle: SmallInt);
procedure RemoveRotated(ACol,ARow: Integer);
function IsRotated(ACol,ARow: Integer;var aAngle: Integer): Boolean;
Adding 90 degrees rotated text is as such easy:
Grid.AddRotated(2,3,90,’This is rotated’);
Comments
A comment indicator is a little triangle in the right top corner of the cell that indicates a comment
text is available for the cell. When the mouse is over the comment indicator, this comment is
displayed as a hint. The color of the little triangle comment indicator is red by default but can be
set in another color with the property grid.ControlLook.CommentColor: TColor or it can be set as
parameter of the method AddColorComment.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
70 | P a g e
This is an overview of comment related methods & properties:
procedure AddComment(ACol,ARow: Integer; Comment:string);
Adds a comment with default color to cell ACol,ARow.
procedure AddColorComment(ACol,ARow: Integer; Comment:string; Color:
TColor);
Adds a comment with color to cell ACol,ARow.
procedure RemoveComment(ACol,ARow: Integer);
Removes the comment from cell ACol,ARow.
procedure RemoveAllComments;
Removes comments from all cells in the grid.
function IsComment(ACol,ARow: Integer;var comment:string): Boolean;
The IsComment method returns true when the specified cell effectively contains a comment and it
returns this comment text in the comment parameter.
property CellComment[ACol,ARow: integer]: string;
Provides access to cell comments as property.
Checkbox and DataCheckbox
Three types of checkboxes exist. A normal checkbox can be added to a cell with some text. The
checkbox state is set through the SetCheckBoxState method. A normal checkbox can have two
states: checked and not checked. When checked, its state is true, when unchecked, its state is
false. The second type checkbox is a tri-state checkbox. Notice the overrides for the methods
AddCheckBox, GetCheckBoxState, SetCheckBoxState. When used with Boolean parameters, this
applies to normal two state checkboxes. When used with the TCheckBoxState parameter, this
applies to tri-state checkboxes that can have the states: cbChecked, cbUnchecked, cbGrayed. A
third checkbox type is the data checkbox. A data checkbox is added to a cell and the checkbox
state reflects the cell text. If the cell text is equal to the grid.CheckTrue property, the checkbox is
displayed as checked, if the cell text is equal to the grid.CheckFalse property, the checkbox is
displayed as not checked. The checkbox is displayed grayed when the cell is set to readonly with
the OnCanEditCell event. If it is not desirable that a checkbox looks disabled for readonly cells, set
grid.NoDisabledCheckRadioLook = true. If a data checkbox is used, clicking the checkbox will cause
the cell text to change from grid.CheckFalse to grid.CheckTrue or vice versa.
This is an overview of methods that can be used with checkboxes:
procedure AddCheckBox(ACol,ARow: Integer;State,Data: Boolean); overload;
procedure AddCheckBox(ACol,ARow: State: TCheckBoxState); overload;
procedure RemoveCheckBox(ACol,ARow: Integer);
function HasCheckBox(ACol,ARow: Integer): Boolean;
function HasDataCheckBox(ACol,ARow: Integer): Boolean;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
71 | P a g e
function GetCheckBoxState(ACol,ARow: Integer;var state: Boolean): Boolean;
function GetCheckBoxState(ACol,ARow: Integer;var state: TCheckBoxState):
Boolean;
function SetCheckBoxState(ACol,ARow: Integer;state: Boolean): Boolean;
function SetCheckBoxState(ACol,ARow: Integer;state: TCheckBoxState):
Boolean;
function ToggleCheckBox(ACol,ARow: Integer): Boolean;
procedure AddCheckBoxColumn(ACol: Integer);
procedure AddTriStateCheckBoxColumn (ACol: Integer);
procedure RemoveCheckBoxColumn(ACol: Integer);
Example: counting the number of checked checkboxes in a column
var
I,Num: integer;
State: Boolean;
begin
Num := 0;
for I := grid.FixedRows to grid.RowCount 1 do
begin
if grid.GetCheckboxState(Col,I,State) then
if State then inc(Num);
end;
end;
Example: alternative to count checked data checkboxes
Supposing the checkboxes have been added with grid.AddCheckBox(Col,Row,False,True);
var
I,Num: integer;
begin
Num := 0;
for I := grid.FixedRows to grid.RowCount 1 do
begin
if grid.Cells[Col,I] = grid.CheckTrue then
inc(Num);
end;
end;
Three events can be triggered from the checkbox, the OnCheckboxClick, OnCheckboxMouseUp and
the OnCheckBoxChange event. The OnCheckBoxChange event is triggered whenever the state of a
checkbox changes as a result from a click of the user on the grid. Note that the OnCheckBoxChange
event will also be triggered for each checkbox changing its state by a click on a column header
checkbox.
Sometimes, it is desirable to have a checkbox in a fixed column header cell that can immediately
check or uncheck all checkboxes in the column. It is easy to have this type of functionality in
TAdvStringGrid:
with AdvStringGrid1 do
Begin
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
72 | P a g e
Options := Options + [goEditing];
AddCheckBoxColumn(1);
AddCheckBox(1,0,false,false);
MouseActions.CheckAllCheck := true;
end;
Programmatically, the entire column of checkboxes can be checked or unchecked with the methods:
procedure CheckAll(Col: Integer);
procedure UnCheckAll(col: Integer);
Radiobuttongroups
To add a radiobuttongroup to the grid, a stringlist is used for the text associated with each
radiobutton. With the AddRadio and CreateRadio methods the same logic is applied to a stringlist
maintained by the grid and a stringlist maintained by the application as for a bitmap with the
AddBitmap and CreateBitmap methods. The direction of the radiobuttons in the grid cell is set with
the DirRadio parameter and can be horizontal (DirRadio = 0) or vertical (DirRadio = 1).
procedure AddRadio(ACol,ARow,DirRadio,IdxRadio: Integer; sl:TStrings);
function CreateRadio(ACol,ARow,DirRadio,IdxRadio: Integer): TStrings;
procedure RemoveRadio(ACol,ARow: Integer);
function IsRadio(ACol,ARow: Integer): Boolean;
function GetRadioIdx(ACol,ARow: Integer;var IdxRadio: Integer): Boolean;
function SetRadioIdx(ACol,ARow,IdxRadio: Integer): Boolean;
function GetRadioStrings(ACol,ARow: Integer): TStrings;
Example: adding radiobuttons maintained by the application
var
i:integer;
begin
radopt1 := TStringList.Create;
radopt1.Add('Delphi');
radopt1.Add('C++Builder');
radopt1.Add('JBuilder');
radopt2 := TStringList.Create;
radopt2.Add('Std');
radopt2.Add('Prof');
radopt2.Add('C/S');
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
73 | P a g e
with AdvStringGrid1 do
begin
for I := 1 to RowCount - 1 do
begin
AddRadio(1,i,0,-1,radopt1);
AddRadio(2,i,1,-1,radopt2);
end;
end;
end;
To get the radiobutton index, the GetRadioIdx can be used which returns in the RadioIdx parameter
the value of the selected radiobutton or -1 if no radiobutton is selected.
Example: getting the selected radiobutton
var
Idx: Integer;
if Grid.GetRadioIdx(2,3,idx) then
ShowMessage(‘Radiobutton ‘+inttostr(idx)+’ selected’);
The radiobuttongroups trigger two events : OnRadioClick and OnRadioMouseUp
RadioButton columns
Instead of having a radiogroup in a single cell, it is also possible to add a radiogroup in a column of
the grid. Following methods are provided to handle radio button groups in grid columns:
procedure AddRadioButton(ACol,ARow: integer; State:Boolean = false);
procedure AddRadioButtonGroup(ACol,ARow: integer; Group: TRadioButtonGroup;
State:Boolean = false);
procedure RemoveRadioButton(ACol,ARow: integer);
function HasRadioButton(ACol,ARow: integer): boolean;
function HasRadioButtonGroup(ACol,ARow: integer): boolean;
function IsRadioButtonChecked(ACol,ARow: integer): boolean;
function SetRadioButtonState(ACol, ARow: integer; State: boolean): boolean;
procedure AddRadioButtonColumn(ACol: integer);
procedure RemoveRadioButtonColumn(ACol: integer);
procedure SetRadioButtonColumnIndex(ACol, Index: integer);
function GetRadioButtonColumnIndex(ACol: integer): integer;
The radiobutton in a cell triggers the event : OnRadioButtonClick
In this sample code, two columns of 3 radiobutton cells are created:
procedure TForm1.FormCreate(Sender: TObject);
begin
AdvStringGrid1.Options := AdvStringGrid1.Options + [goEditing];
AdvStringGrid1.AddRadioButton(1,1,true);
AdvStringGrid1.AddRadioButton(1,2);
AdvStringGrid1.AddRadioButton(1,3);
AdvStringGrid1.Cells[1,1] := 'France';
AdvStringGrid1.Cells[1,2] := 'Germany';
AdvStringGrid1.Cells[1,3] := 'United Kingdom';
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
74 | P a g e
AdvStringGrid1.AddRadioButton(2,1,true);
AdvStringGrid1.AddRadioButton(2,2);
AdvStringGrid1.AddRadioButton(2,3);
AdvStringGrid1.Cells[2,1] := 'Paris';
AdvStringGrid1.Cells[2,2] := 'Berlin';
AdvStringGrid1.Cells[2,3] := 'London';
AdvStringGrid1.AutoSizeCol(1);
AdvStringGrid1.AutoSizeCol(2);
end;
To create small groups of cells that form a radiogroup, the method AddRadioButtonGroup can be
used. This method has an extra parameter with which it can be defined whether adjacent cells form
a row of radiobuttons or column of radiobuttons. Note that in groups each radiobutton remains
individually accessible and its state can be individually checked or unchecked.
This code snippet demonstrates how 3 groups of 2 radiobuttons can be created:
begin
AdvStringGrid1.AddRadioButtonGroup(1,1,rgRow);
AdvStringGrid1.AddRadioButtonGroup(2,1,rgRow);
AdvStringGrid1.Cells[1,1] := 'Group A1';
AdvStringGrid1.Cells[2,1] := 'Group A2';
AdvStringGrid1.AddRadioButtonGroup(4,1,rgRow);
AdvStringGrid1.AddRadioButtonGroup(5,1,rgRow);
AdvStringGrid1.Cells[4,1] := 'Group B1';
AdvStringGrid1.Cells[5,1] := 'Group B2';
AdvStringGrid1.AddRadioButtonGroup(3,4,rgCol);
AdvStringGrid1.AddRadioButtonGroup(3,5,rgCol);
AdvStringGrid1.Cells[3,4] := 'Group C1';
AdvStringGrid1.Cells[3,5] := 'Group C2';
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
75 | P a g e
Button and BitButtons
Always visible buttons and buttons with a bitmap can be added to cells in the grid. The width and
height of these buttons can be set as well as the caption and/or glyph. This is achieved through
following methods:
procedure AddButton(ACol,ARow, bw, bh:
Integer;Caption:string;hal:TCellHalign;val:TCellValign);
procedure SetButtonText(ACol,ARow: Integer; Caption: string);
procedure PushButton(ACol,ARow: Integer;push: Boolean);
procedure RemoveButton(ACol,ARow: Integer);
function HasButton(ACol,ARow: Integer): Boolean;
procedure AddBitButton(ACol,ARow,bw,bh:Integer; Caption:string;
Glyph:TBitmap; hal:TCellHalign; val:TCellValign);
function CreateBitButton(ACol,ARow,bw,bh: Integer; Caption:string;
hal:TCellHalign; val:TCellValign): TBitmap;
Again the same approach for adding buttons with a bitmap maintained by the grid and one by the
application is provided with the AddBitButton and CreateBitButton method. For the first method
AddBitButton, the application needs to create, maintain and destroy the bitmap, for the
CreateBitButton method the grid creates, maintains and eventually destroys the bitmap.
The buttons fire the OnButtonClick event when clicked.
Note: by design, a button in a read-only cell is disabled. If this behavior is not desired, set
grid.ControlLook.NoDisabledButtonLook = True.
Expanding and collapsing rows
When cells contain more data than you want to have always visible, adding a row expand/collaps
button can be convenient. This is a small button in the top right corner of a cell. When clicked, it
will increase the row height, making more data visible and when clicked again, it reduces the row
height back to the normal height. Adding expand/collaps buttons in the grid is easy. Five functions
controls the expand/collaps behavior in the grid:
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
76 | P a g e
procedure AddExpandButton(ACol,ARow, ExpandedHeight: Integer);
function HasExpand(ACol,ARow: Integer): Boolean;
procedure RemoveExpand (ACol,ARow: Integer);
procedure ToggleExpand(ACol,ARow: Integer);
function GetExpandState(ACol,ARow: Integer): Boolean;
function GetExpandHeight(ACol,ARow:Integer; Expand:Boolean): Integer;
The AddExpandButton() function will add an expander button to a cell. The ExpandedHeight
parameter sets the height of the row in expanded state. The collapsed row height is by default the
height of the row before the row gets expanded. The function HasExpand() will return true when a
grid has such expand/collaps button and RemoveExpand() will remove any existing expand/collaps
button from the cell. ToggleExpand() will simply toggle the state of the row from collaps to expand
and vice versa. Finally, the function GetExpandState() will return true when the row is in expanded
state or false when not. The GetExpandHeight() function will return the height of an expanded row
when the Expand parameter is true and the normal height of the row when Expand parameter is
false.
Progressbars and ProgressPie
Two types of progress indicators can be displayed in a grid cell: a rectangular progress bar and a
circular pie type progress indicator. The AddProgress method provides two color parameters, one
for the zero to current position part of the progress bar and one for the current position to end part
of the bar. With the AddProgressEx method, additional color settings for font color in both parts is
possible. The progress bar fills the complete cell and as such the position of the progress bar
reflects a value between 0 and 100 set in the cell text.
procedure AddProgress(ACol,ARow: Integer;FGColor,BKColor: TColor);
procedure AddProgressEx(ACol,ARow:
Integer;FGColor,FGTextColor,BKColor,BKTextColor: TColor);
procedure AddProgressFormatted(ACol,ARow:
Integer;FGColor,FGTextColor,BKColor,BKTextColor: TColor; Fmt: string; Min,
Max: Integer);
procedure RemoveProgress(ACol,ARow: Integer);
procedure AddAdvProgress(ACol,ARow: Integer;Min:integer=0;Max:integer=100);
procedure RemoveAdvProgress(ACol,ARow: Integer);
Example: adding progressbar and setting position to 50
Grid.AddProgress(2,3,clRed,clWhite);
Grid.Ints[2,3] := 50;
A method is available AddProgressFormatted that allows to include the numeric formatting of the
value in the progressbar, as shown in this code snippet:
begin
AdvStringGrid1.AddProgressFormatted(1,1,clRed,clBlack,clInfoBk,clBlue,'%d
kb/sec',0,1000);
AdvStringGrid1.Ints[1,1] := 565;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
77 | P a g e
Adding an advanced progress bar:
Using grid.AddAdvProgress, it is possible to add a Windows themed style progressbar (available from
Windows XP or higher) with many additional options. The settings for the progressbar appearance
can be found under Grid.ProgressAppearance. This allows to have progressbars with colors
dependent on level of progress. This sample code adds three XP style progressbars to the grid with
default progress level color settings:
with AdvStringGrid1 do
begin
ProgressAppearance.CompletionSmooth := false;
AddAdvProgress(1,1);
Ints[1,1] := 50;
AddAdvProgress(1,2);
Ints[1,2] := 75;
AddAdvProgress(1,3);
Ints[1,3] := 91;
end;
The circular pie type progress bar allows a compact visual progress indication in a cell that can
contain text as well. The value of the progress pie is set with the method SetProgressPie.
procedure AddProgressPie(ACol,ARow: Integer; Color: TColor; Value:
Integer);
procedure SetProgressPie(ACol,ARow: Integer; Value: Integer);
procedure RemoveProgressPie(ACol,ARow: Integer);
Example: adding progress pie with text and position 25
Grid.AddProgressPie(2,3,clLime,25);
Grid.Cells[2,3] := ‘25% completion’;
The progress pie is always left aligned in the cell and before the optional text in the cell.
Note: the style of the progress bar is also affected by the ControlLook property. This is discussed in
detail for the ControlLook property.
Range Indicator
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
78 | P a g e
A range indicator can show negative and positive ranges of value visually as bars in 2 different
colors, a color for negative range and a color for a positive range. The method to add a range
indicator is:
AddRangeIndicator(Col,Row,Range,NegColor,PosColor,ShowValue);
with:
Col,Row: cell where to add range indicator
Range: min/max boundaries of range, ie. From Range to +Range (default 100)
NegColor: color of negative range bar (default Red)
PosColor: color of positive range bar (default Black)
ShowValue: when true shows value (default False)
Such range indicator is added with:
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
begin
for i := 1 to AdvStringGrid1.RowCount - 1 do
begin
AdvStringGrid1.AddRangeIndicator(1,i,100,clRed,clGreen,false);
AdvStringGrid1.Ints[1,i] := -100 + Random(200);
end;
end;
Balloons
A balloon appears when the mouse hovers over a cell. A balloon features 3 elements: a title, a text
and an icon. To add and remove balloons, following methods are available:
procedure AddBalloon(ACol,ARow: Integer; Title, Text:string; Icon:
TBalloonIcon);
procedure RemoveBalloon(ACol, ARow: integer);
function HasBalloon(ACol, ARow: integer): boolean;
function IsBalloon(ACol, ARow: integer; var Title, Text: string; var Icon:
TBalloonIcon): boolean;
TBalloonIcon is defined as:
biNone: no icon
biInfo: information icon
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
79 | P a g e
biWarning: warning icon
biError: error icon
Adding a balloon can be done with:
procedure TForm2.FormCreate(Sender: TObject);
begin
AdvStringGrid1.Balloon.Enable := true;
AdvStringGrid1.AddBalloon(2,2,'Title A','Cell 2,2 is here', biError);
AdvStringGrid1.AddBalloon(3,3,'Title B','Cell 3,3 is here', biWarning);
end;
Note: in order to display a balloon, either via method AddBalloon or dynamically via the event
OnCellBalloon, grid.Balloon.Enable must be set to true. Further settings for the balloon tooltips are
available through grid.Balloon with properties:
AutoHideDelay: integer;
Sets the delay in milliseconds to auto hide the
balloon.
BackgroundColor: TColor;
Sets the background color of the balloon tooltip.
Enable: Boolean;
When true, displaying balloon tooltips is enabled.
InitialDelay: integer;
Sets the delay in milliseconds to wait before the
first balloon tooltip is shown.
ReshowDelay: integer;
Sets the delay in milliseconds to wait before a
new balloon tooltip is shown.
TextColor: TColor;
Sets the text color of the balloon tooltip.
Transparency: integer;
Sets the transparency of the balloon tooltip.
Shapes
Often it is desirable to have a little graphic representation and not having to resort to image
resources for this makes it easy to have graphics in many colours and many shapes in a resource
friendly way. The grid offers a range of such shapes that can be added via the method
grid.AddShape(ACol,ARow: integer; Shape: TCellShape; FillColor,LineColor: TColor; hal:
TCellHAlign; val: TCellVAlign);
The type TCellShape is defined in the unit AdvUtil and the supported shapes are:
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
80 | P a g e
csRectangle rectangular
csCircle circle
csTriangleLeft left oriented triangle
csTriangleRight right oriented triangle
csTriangleUp up oriented triangle
csTriangleDown down oriented triangle
csDiamond diamond shape
csLineVert single vertical line
csLineHorz single horizontal line
csRoundRect rounded rectangle
csEllips ellips
csSquare square
csRoundSquare rounded square
csStar star
csArrowUp arrow up
csArrowDown arrow down
csArrowLeft arrow left
csArrowRight arrow right
csHalfStar half star
To demonstrate this, following code adds 4 different shapes to the grid:
begin
AdvStringGrid1.AddShape(1,1,csDiamond,clLime, clSilver,
haBeforeText,vaTop);
AdvStringGrid1.AddShape(1,2,csCircle,clRed, clSilver,
haBeforeText,vaTop);
AdvStringGrid1.AddShape(1,3,csStar,clYellow, clSilver,
haBeforeText,vaTop);
AdvStringGrid1.AddShape(1,4,csArrowUp,clBlue, clSilver,
haBeforeText,vaTop);
end;
Rating control
As commonly seen in many web interfaces, the grid provides a specific graphic type to add a rating
control to a cell. The rating control consists of a number of star shapes. The number of fully or half
coloured stars represents the value. To add a rating control to a cell, call
grid.AddRating(ACol,ARow,Scale: integer; FullColor,EmtpyColor: TColor). The parameters
ACol,ARow set the cell where to add the rating control. The Scale parameter sets the number of
stars to use in the rating control and the parameters FullColor,EmptyColor set the color for fully
coloured stars and non coloured stars. When the grid cell is not read-only, the value of the rating
control can be change by clicking on the cell. The value can also be programmatically set and
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
81 | P a g e
retrieved with grid.Floats[Col,Row]: double. This example code adds 3 rating controls in the grid
and presets its values:
begin
AdvStringGrid1.AddRating(1,1,5,clLime,clSilver);
AdvStringGrid1.Floats[1,1] := 2.0;
AdvStringGrid1.AddRating(1,2,5,clLime,clSilver);
AdvStringGrid1.Floats[1,2] := 3.6;
AdvStringGrid1.AddRating(1,3,5,clLime,clSilver);
AdvStringGrid1.Floats[1,3] := 1.1;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
82 | P a g e
Using a vertical scrollbar per cell in TAdvStringGrid
When text is too large to fit in a cell, you could increase the cell size, ie. increase the row height,
the column width or both. This is not always practical, as the higher the row height is, the less rows
can be displayed. The same applies for the column width. The text could also be displayed cut-off
but this solution is also far from ideal. Now, an alternative solution is available with the capability
to add a vertical scrollbar to a cell. Any cell can as such have its own scrollbar and scroll separately
the cell's text or HTML formatted text. This feature is made available with the grid.AddScrollbar()
method. With this method a scrollbar is added to a cell. The scrollbar range and pagesize can either
be automatically set according to the size of the text in a cell or can be programmatically set. <br>
This is an overview of the methods available:
grid.AddScrollbar(col,row: integer; AutoRange: Boolean);
Adds a scrollbar to cell col,row and when AutoRange is true, the scrollbar range and pagesize is
automatically calculated.
grid.RemoveScrollbar(col,row: integer);
Removes the scrollbar again from the cell
grid.HasScrollBar(col,row: integer): Boolean
Returns true when the cell col,row has a scrollbar
grid.HasAutoRangeScrollBar(col,row: integer): Boolean
Returns true when the cell col,row has an autorange scrollbar
grid.SetScrollPosition(col,row,position: integer);
Programmatically sets the position of the scrollbar in cell col,row
grid.GetScrollPosition(col,row,position: integer): integer;
Programmatically gets the position of the scrollbar in cell col,row
grid.SetScrollProp(col,row: integer; Prop: TScrollProp);
Sets the scrollbar range & pagesize
grid.GetScrollProp(col,row: integer): TScrollProp;
Gets the scrollbar range & pagesize
In the sample, these capabilities are demonstrated by adding very long HTML formatted text in 3
cells of the grid. In these cells, first an autorange scrollbar was added with:
AdvStringGrid1.AddScrollBar(2,1,true);
AdvStringGrid1.AddScrollBar(2,2,true);
AdvStringGrid1.AddScrollBar(2,3,true);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
83 | P a g e
When text is set in a cell, the scrollbar will then appear when necessary. In this sample, it is also
demonstrated how the scrollbar position can be programmatically set. This is done from an UpDown
control for the cell that is selected. Upon cell selection, the UpDown control is initialized to the
cell's scrollbar range:
procedure TForm2.AdvStringGrid1SelectCell(Sender: TObject; ACol, ARow:
Integer;
var CanSelect: Boolean);
var
sp: TScrollProp;
begin
if AdvStringgrid1.HasScrollBar(Acol,ARow) then
begin
sp := AdvStringgrid1.GetScrollProp(ACol,ARow);
updown1.Min := 0;
updown1.Max := sp.Range;
updown1.Position := sp.Range -
AdvStringgrid1.GetScrollPosition(ACol,ARow);
end;
end;
procedure TForm2.UpDown1Changing(Sender: TObject; var AllowChange:
Boolean);
var
sp: TScrollProp;
begin
if AdvStringGrid1.HasScrollBar(AdvStringgrid1.Col, AdvStringGrid1.Row)
then
begin
AdvStringGrid1.SetScrollPosition(AdvStringgrid1.Col,
AdvStringGrid1.Row, updown1.Max - updown1.Position);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
84 | P a g e
end;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
85 | P a g e
TAdvStringGrid HTML formatted cells
The cells in TAdvStringgrid have support for various HTML tags through which fine control of the
display is possible. The HTML formatting support is by default enabled but can be turned off by
setting the property EnableHTML to False. The supported tags form a subset of the HTML tags and
are further named as mini html
Supported tags
B : Bold tag
<B> : start bold text
</B> : end bold text
Example : This is a <B>test</B>
U : Underline tag
<U> : start underlined text
</U> : end underlined text
Example : This is a <U>test</U>
I : Italic tag
<I> : start italic text
</I> : end italic text
Example : This is a <I>test</I>
S : Strikeout tag
<S> : start strike-through text
</S> : end strike-through text
Example : This is a <S>test</S>
A : anchor tag
<A href="value" title=”HintValue”> : text after tag is an anchor. The 'value' after the href
identifier is the anchor. This can be an URL (with ftp,http,mailto,file identifier) or any text.
If the value is an URL, the shellexecute function is called, otherwise, the anchor value can
be found in the OnAnchorClick event
</A> : end of anchor
Examples :
This is a <A href="mailto:myemail@mail.com">test</A>
This is a <A href="http://www.tmssoftware.com">test</A>
This is a <A href="somevalue">test</A>
Hints for hyperlinks defined in HTML can also be directly be set with the Title attribute. If
no Title attribute is specified, the HREF value is used as hint value. Hyperlink hints are
enabled when grid.AnchorHint is set to true and grid.ShowHint is set to true.
Example:
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
86 | P a g e
The hint for this cell is set by:
advstringgrid1.Cells[1,3] := 'A cell <a href="http://www.tmssoftware.com"
title="TMS software">hyperlink</a>';
FONT : font specifier tag
<FONT face='facevalue' size='sizevalue' color='colorvalue' bgcolor='colorvalue'> : specifies
font of text after tag.
with
- face : name of the font
- size : HTML style size if smaller than 5, otherwise pointsize of the font
- color : font color with either hexidecimal color specification or Borland style color name,
ie clRed,clYellow,clWhite ... etc
- bgcolor : background color with either hexidecimal color specification or Borland style
color name
</FONT> : ends font setting
Examples :
This is a <FONT face="Arial" size="12" color="clRed">test</FONT>
This is a <FONT face="Arial" size="12" color="#FF0000">test</FONT>
P : paragraph
<P align="alignvalue" [bgcolor="colorvalue"]> : starts a new paragraph, with left, right or
center alignment. The paragraph background color is set by the optional bgcolor parameter.
</P> : end of paragraph
Example : <P align="right">This is a test</P>
Example : <P align="center">This is a test</P>
Example : <P align="left" bgcolor="#ff0000">This has a red background</P>
Example : <P align="right" bgcolor="clYellow">This has a yellow background</P>
HR : horizontal line
<HR> : inserts linebreak with horizontal line
BR : linebreak
<BR> : inserts a linebreak
BODY : body color / background specifier
<BODY bgcolor="colorvalue" background="imagefile specifier"> : sets the background color of
the HTML text or the background bitmap file
Example :
<BODY bgcolor="clYellow"> : sets background color to yellow
<BODY background="file://c:\test.bmp"> : sets tiled background to file test.bmp
IND : indent tag
This is not part of the standard HTML tags but can be used to easily create multicolumn text
<IND x="indent"> : indents with "indent" pixels
Example :
This will be <IND x="75">indented 75 pixels.
IMG : image tag
<IMG src="specifier:name" [align="specifier"] [width="width"] [height="height"]
[alt="specifier:name"] > : inserts an image at the location
specifier can be :
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
87 | P a g e
idx : name is the index of the image in the associated imagelist
ssys : name is the index of the small image in the system imagelist or a filename for which
the corresponding system imagelist is searched
lsys : same as ssys, but for large system imagelist image
file : name is the full filename specifier
res : name of a resource bitmap (not visible at design time)
no specifier : name of image in an PictureContainer
Optionally, an alignment tag can be included. If no alignment is included, the text
alignment with respect to the image is bottom. Other possibilities are : align="top" and
align="middle"
The width & height to render the image can be specified as well. If the image is embedded
in anchor tags, a different image can be displayed when the mouse is in the image area
through the Alt attribute.
Examples :
This is an image <IMG src="idx:1" align="top">
This is an image <IMG src="ssys:1"> and another one <IMG src="ssys:worfile.doc">
This is an image <IMG src="file://c:\my documents\test.bmp">
This is an image <IMG src="res://BITMAP1">
This is an image <IMG src="name">
SUB : subscript tag
<SUB> : start subscript text
</SUB> : end subscript text
Example : This is <SUP>9</SUP>/<SUB>16</SUB> looks like 9/16
SUP : superscript tag
<SUP> : start superscript text
</SUP> : end superscript text
BLINK : blink tag (the EnableBlink needs to be set to true to enable this)
<BLINK> : start blinking text
</BLINK> : stop blinking text
Example : This is <FONT color="clred"><BLINK>blinking red</BLINK></FONT>text.
UL : list tag
<UL> : start unordered list tag
</UL> : end unordered list
Example :
<UL>
<LI>List item 1
<LI>List item 2
<UL>
<LI> Sub list item A
<LI> Sub list item B
</UL>
<LI>List item 3
</UL>
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
88 | P a g e
LI : list item
<LI [type="specifier"] [color="color"] [name="imagename"]> : new list item
specifier can be "square" or "circle" or "image" bullet color sets the color of the square or
circle bullet imagename sets the PictureContainer image name for image to use as bullet
SHAD : text with shadow
<SHAD> : start text with shadow
</SHAD> : end text with shadow
Z : hidden text
<Z> : start hidden text
</Z> : end hidden text
HI : hilight
<HI> : start text hilighting
</HI> : stop text hilighting
E : Error marking
<E> : start error marker
</E> : stop error marker
Special characters
Following standard HTML special characters are supported :
&lt; : less than : <
&gt; : greater than : >
&amp; : &
&quot; : "
&nbsp; : non breaking space
&trade; : trademark symbol
&euro; : euro symbol
&sect; : section symbol
&copy; : copyright symbol
&para; : paragraph symbol
HTML formatting related events
The hyperlinks that can be added inside a cell cause following events when the mouse is over or
clicked on hyperlink. The events are :
OnItemAnchorClick : triggered when a hyperlink is clicked in a cell
OnItemAnchorEnter : triggered when the mouse enters a hyperlink
OnItemAnchorExit : triggered when the mouse leaves a hyperlink
OnItemAnchorHint : triggered when the mouse is over a hyperlink to query the hint for the link
(this is enabled if the property grid.AnchorHint is set true)
Example: Handling hyperlink clicks in TAdvStringGrid
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
89 | P a g e
A hyperlink is added with
grid.Cells[0,0] :=
‘This is a <a href=”myhyperlink”>hyperlink<a>’;
When the mouse clicked on the hyperlink, the OnItemAnchorClick is called with a reference to
the cell coordinates and the Anchor parameter is ‘myhyperlink’. The AutoHandle parameter is
by default true and causes that the grid will automatically open the default application for the
hyperlink. Setting this parameter AutoHandle allows custom handling of the hyperlink click.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
90 | P a g e
TAdvStringGrid HTML forms
Combining multiple buttons in a cell, adding more than one checkbox in a cell, editing different
items in a cell, it is possible with TAdvStringGrid and its mini HTML forms. Mini HTML forms bring a
solution allowing unlimited capabilities to specify cell contents and behaviour.
TAdvStringgrid, controls can be specified through a the tag <CONTROL>
The CONTROL tag takes following parameters:
<CONTROL ID="ControlID" VALUE="ControlValue" TYPE="ControlType" WIDTH="ControlWidth"
MAXLEN=”ControlMaxLenValue”>
with:
ControlID = unique ID string per cell for the control
ControType = "EDIT" or "CHECK" or "RADIO" or "COMBO" or "BUTTON"
ControlWidth = width of the control in pixels
ControlValue = value of the control depending on the type :
ControlMaxLenValue = optional maximum edit length of edit control. When MAXLEN attribute is not
specified or value of ControlMaxLenValue is 0, string length is not limited.
"TRUE", "FALSE" for checkboxes and radiobuttons
Button caption for button control
Text value for edit and combobox controls
With this information, forms can be specified like:
with AdvStringGrid1 do
begin
Cells[1,ARow] := '<CONTROL TYPE="CHECK" WIDTH="15" ID="CK1"> <b>Patient
information</b> :<BR>' +
'Name : <CONTROL TYPE="EDIT" WIDTH="80" VALUE="" ID="ED1"> '+
'Prename : <CONTROL TYPE="EDIT" WIDTH="80" VALUE="" ID="ED2"> ' +
'<CONTROL TYPE="BUTTON" WIDTH="80" VALUE="Clear" ID="BTN1"><BR><BR>' +
'<IMG src="idx:0" align="middle"> Available : <CONTROL TYPE="COMBO"
WIDTH="60" ID="CO1"> ' +
'<IMG src="idx:1" align="middle"> Payment : <CONTROL TYPE="COMBO"
WIDTH="80" VALUE="" ID="CO2"> '+
'<IMG src="idx:2" align="middle"> Last visit : <CONTROL TYPE="EDIT"
WIDTH="80" VALUE="" ID="ED3">';
end;
Getting and setting control values is done with the property grid.ControlValues[Col,Row,ID]: string;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
91 | P a g e
Example: setting form values through the control ID and ControlValues property:
with AdvStringGrid1 do
begin
ControlValues[1,ARow,'CK1'] := 'TRUE';
ControlValues[1,ARow,'ED1'] := 'Name'+IntToStr(ARow);
ControlValues[1,ARow,'ED2'] := 'PreName'+IntToStr(ARow);
ControlValues[1,ARow,'CO1'] := 'MO';
ControlValues[1,ARow,'CO2'] := 'VISA';
ControlValues[1,ARow,'ED3'] := DateToStr(Now + ARow);
end;
The events that are used for handling form controls are :
OnControlClick : event triggered when a mini HTML form control is clicked
OnControlComboList : event querying the values for a combobox as well as its style
OnControlEditDone : event triggered when editing of the mini HTML form control starts
All events return the cell for the control, the control ID, type and value. For the
OnControlComboList event, a stringlist is passed as parameter where the values that need to be
displayed in the combobox can be added. With the Edit parameter, the combobox can be set as
either dropdownlist (Edit = False) or as editable combobox (Edit = true).
Example: Using the OnControlComboList event for setting combobox items in a form:
procedure TForm1.AdvStringGrid1ControlComboList(Sender: TObject; ARow,
ACol: Integer; CtrlID, CtrlType, CtrlVal: String; Values: TStringList;
var Edit: Boolean; var DropCount: Integer);
begin
Values.Clear;
if CtrlID = 'CO1' then
begin
Values.Add('MO');
Values.Add('TU');
Values.Add('WE');
Values.Add('TH');
Values.Add('FR');
Values.Add('SA');
Values.Add('SU');
Edit := False; // combo dropdownlist
end;
if CtrlID = 'CO2' then
begin
Values.Add('VISA');
Values.Add('AMEX');
Values.Add('MASTERCARD');
Values.Add('CASH');
Values.Add('N/A');
Edit := True; // combo dropdown edit
end;
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
92 | P a g e
TAdvStringGrid miscellaneous display control
Showing active cell in fixed cells
With the property ActiveCellShow set true, it is possible to indicate the fixed row and column cell
for column and row where the focus cell is found, in a different color and different font. The
background color of the fixed cell is set with ActiveCellColor, the font is set with the ActiveCellFont
property. For normal display, the fixed cell uses the FixedColor background color and FixedFont for
text.
Note: when active cell display is activated and multiple fixed columns or fixed rows are shown in
the grid, the active cells are displayed on the innermost fixed columns/rows.
Background gradient or bitmap
TAdvStringGrid can show a bitmap or gradient as background in fixed cells only, normal cells only or
for all cells. The background bitmap is set with the grid.BackGround.Bitmap property. The selection
for which cells the background should be displayed is set with grid.BackGround.Cells. This
background bitmap can be tiled (grid.BackGround.Display = bdTile) or displayed at a fixed
(grid.BackGround.Display = bdFixed) position (set with grid.BackGround.Top and
grid.BackGround.Left)
To show a background gradient, set grid.Background.Display to bdGradientVert or bdGradientHorz
and select gradient start and end color with grid.Background.Color and grid.Background.ColorTo.
Bands
Banding of alternate colors is enabled in TAdvStringGrid with setting grid.Bands.Active = True.
The alternating colors are set with grid.Bands.PrimaryColor and grid.Bands.SecondaryColor. The
number of rows to display in primary color is set with grid.Bands.PrimaryLength, the number of rows
to display in secondary color is set with grid.Bands.SecondaryLength. Finally, it can be selected
whether the banding should be printed or not with the grid.Bands.Print property.
Note: when using a descendent class such as TAdvColumnGrid or TDBAdvGrid, it is required to set
the property ShowBands = true for the columns where bands should be displayed.
Control look
Various settings are combined here that control how inplace controls look in the grid. The
ControlLook property has following subproperties:
ButtonPrefix: Boolean;
When true, a & character is treated as shortcut prefix
and makes the next letter shortcut character that is
displayed underlined. When ButtonPrefix = false, the
& character is displayed literally in the button
control.
CheckAlwaysActive: Boolean;
When true, a checkbox is always displayed as active,
irrespective of the readonly state of the cell
CheckedGlyph: TBitmap;
Sets the glyph for a custom checked checkbox
CheckSize: Integer;
Sets the size of a checkbox
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
93 | P a g e
Color: TColor;
Sets the color for Borland style checkbox and
radiobuttons
CommentColor: TColor;
Sets the default comment triangle indicator color
ControlStyle: TControlStyle;
See below
DropDownAlwaysVisible: Boolean;
When true, the combobox dropdown button is always
displayed, irrespective of the editing mode
DropDownCount: integer;
Sets the nr. of items displayed in the dropdown of
inplace combobox editors
FixedDropDownButton: Boolean;
When true, a fixed cell has an additional right side
dropdown button when the mouse hovers the cell
FixedGradient*: TColor;
Series of properties that control the top & bottom
gradient of the fixed cell in normal, hot & down
state.
FlatButton: Boolean;
When true, inplace buttons are displayed in flat style
NoDisabledButtonLook: Boolean;
By default, buttons added in the grid in read only
cells are shown as disabled. To override this, set this
property to true.
NoDisabledCheckRadioLook: Boolean
By default, checkboxes and radiobuttons added in the
grid in read only cells are shown as disabled. To
override this, set this property to true.
ProgressBorderColor: TColor;
Sets the color of a progress bar border
ProgressHeight: integer;
Default value is -1 and with this default value, the
progressbar height is equal to the cell height. When a
different value is specified, this is used as height for
the progressbars in grid cells.
ProgressMarginX: Integer;
Horizontal margin on left and right for the
progressbar in a cell
ProgressMarginY: Integer;
Vertical margin on top and below for the progressbar
in a cell
ProgressXP: Boolean;
When true, the progressbar is drawn with the
Windows XP visual style
RadioAlwaysActive: Boolean;
When true, a radiobutton is always displayed as
active, irrespective of the readonly state of the cell
RadioOffGlyph: TBitmap;
Sets the glyph for a custom unchecked radiobutton
RadioOnGlyph: TBitmap;
Sets the glyph for a custom checked radiobutton
RadioSize: Integer;
Sets the size of a radiobutton
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
94 | P a g e
SpinButtonsAlwaysVisible: Boolean;
When true, buttons of spin editor inplace editors are
always visible, irrespective of the editing state of a
cell.
UnCheckedGlyph: TBitmap;
Sets the glyph for a custom unchecked checkbox
The ControlStyle can have following values:
TControlStyle = (csClassic,csFlat,csWinXP,csBorland,csTMS,csGlyph,csTheme);
With:
csBorland
csClassic
csFlat
csGlyph
csTheme
csTMS
csWinXP
Row indicator
With the property grid.RowIndicator: TBitmap a bitmap can be set that is shown in the first fixed
column for the active row. A small arrow bitmap can be set for example to show the active row in a
similar way as the DB cursor is shown in a DB grid.
Global cell text appearance settings
Several grid properties affect global look of cell text which are:
AutoNumAlign
When true, automatically selects right alignment for cells containing numeric data
only
EnhTextSize
When true, text that does not fit in the grid cell is displayed with end ellipsis
MultiLineCells
When true, cell text containing line feeds is displayed on multiple lines
URLFull
When true, the protocol specifier is displayed along with the hyperlink, otherwise
it is used internally but not displayed
URLShow
When true, cell text starting with protocol specifiers http://, ftp://, nntp://,
mailto: is displayed in the URLColor and underlined
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
95 | P a g e
URLShowInText
When true, any hyperlink of the type http://, http://, ftp://, nntp://, mailto:
that occurs in the text of a cell is displayed in the URLColor and underlined and
will act as a hyperlink when clicked. This means that if the cell content is “Visit
http://www.tmssoftware.com for details”, the hyperlink will be automatically
underlined without any need to write HTML <A> tags. This is different from using
just URLShow = true, where the entire cell text is treated as hyperlink or not.
WordWrap
When true, cell text is wordwrapped. This can be dynamically set for individual
cells by using the event OnGetWordWrap. Note that when WordWrap is enabled,
text in the cell is always vertically top aligned. The Windows wordwrap text
drawing API can only display wordwrapped text top aligned.
Cell selection
By default, selected cells are displayed in the clHighLight background color and clHightLightText
font color. Set grid.ShowSelection = false if the grid should not display selected cells. Settings that
control display of selected cells are:
SelectionColor: TColor;
Sets the background color of selected cells
SelectionColorTo: TColor;
When different from clNone, sets the gradient end color of a
selected cell.
SelectionColorMixer: boolean;
When true, the color of a selected cell is X% of color value of the
cell and 100-X% of the selectioncolor. X is the
SelectionColorMixerFactor and defaults to 50.
SelectionColorMixerFactor:
integer;
Selects the ratio of the color mixer between cell color and
selection color.
SelectionMirrorColor: TColor;
When different from clNone, sets the bottom gradient start color
of a selected cell.
SelectionMirrorColorTo: TColor;
When different from clNone, sets the bottom gradient end color
of a selected cell.
SelectionRectangle: Boolean;
When true, a wide border rectangle is displayed around selected
cells
SelectionResizer: Boolean;
When true, the selection rectangle is displayed with rectangular
grip in bottom right corner to resize the selection
SelectionRTFKeep: Boolean;
When true, RTF text colors are not affected by selection text
color in selected cells
SelectionTextColor: TColor;
Sets the text color of selected cells
ShowSelection: Boolean;
When true, selected cells are displayed in SelectionColor and
SelectionTextColor
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
96 | P a g e
The selection in the grid can be hidden temporarily by the method grid.HideSelection and unhidden
later with grid.UnHideSelection.
Note: by default, when the SelectionTextColor is set to a color different from clNone, the
SelectionTextColor has priority over the font color of the cell itself. This is to ensure that for the
combination SelectionColor/SelectionTextColor, the cell text is always guaranteed to be visible. If it
is not desirable that the selection text color is different from the cell font color, set
grid.SelectionTextColor to clNone. With this setting, the cell text color will be always used.
Advanced topic: Smart cell resizing
With SelectionResizer and SelectionRectangle set true, the selection can be resized by dragging the
bottom left corner. If the property grid.Navigation.AllowSmartClipboard is set true as well, the
resizing of the selection will cause the smart clipboard operation to try to fill the new selection
based on the information found in the first selected cells. It will try to guess the data format of the
cells of the original selection and try to find the delta between 2 or more cells of the original
selection and apply this delta for completion for the new selection.
Example: original selection
Resized to new selection
Hilighting and marking errors in cells
With the <HI> tag and <E> tag an arbitrary part of the text can be highlighted or underlined with
error lines. TAdvStringGrid has a range of methods that allow to automatically highlight or
unhighlight text in cells or mark or unmark text in cells. The following set of methods is available
for this:
function HilightText(DoCase: Boolean; S,Text: string):string;
function UnHilightText(S:string):string;
procedure HilightInCell(DoCase: Boolean; Col,Row: Integer; HiText: string);
procedure HilightInCol(DoFixed,DoCase: Boolean; Col: Integer; HiText:
string);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
97 | P a g e
procedure HilightInRow(DoFixed,DoCase: Boolean; Row: Integer; HiText:
string);
procedure HilightInGrid(DoFixed,DoCase: Boolean; HiText: string);
procedure UnHilightInCell(Col,Row: Integer);
procedure UnHilightInCol(DoFixed: Boolean; Col: Integer);
procedure UnHilightInRow(DoFixed: Boolean; Row: Integer);
procedure UnHilightInGrid(DoFixed: Boolean);
function MarkText(DoCase: Boolean; S,Text: string):string;
function UnMarkText(S:string):string;
procedure MarkInCell(DoCase: Boolean; Col,Row: Integer; HiText: string);
procedure MarkInCol(DoFixed,DoCase: Boolean; Col: Integer; HiText: string);
procedure MarkInRow(DoFixed,DoCase: Boolean; Row: Integer; HiText: string);
procedure MarkInGrid(DoFixed,DoCase: Boolean; HiText: string);
procedure UnMarkInCell(Col,Row: Integer);
procedure UnMarkInCol(DoFixed: Boolean; Col: Integer);
procedure UnMarkInRow(DoFixed: Boolean; Row: Integer);
procedure UnMarkInGrid(DoFixed: Boolean);
procedure RemoveMarker(ACol,ARow: Integer);
procedure RemoveAllMarkers;
Example: highlighting TMS in a cell
Grid.Cells[2,3] := ‘This is TMS software’;
Grid.HilightInCell(False,2,3,’TMS’);
This will display the cell as :
This is TMS software
Later the highlighting can be removed by calling grid.UnHiLightInGrid(False). This will remove
highlighting in any cell of the grid.
Trimming cells
Following functions are defined to perform trimming of values in a rectangle of grid cells, in a row,
in a column or in the entire grid:
procedure TrimRect(ACol1,ARow1,ACol2,ARow2: Integer);
procedure TrimCol(ACol: Integer);
procedure TrimRow(ARow: Integer);
procedure TrimAll;
Automatic sizing and numbering of columns and rows
TAdvStringGrid has several built-in methods to let the grid automatically adapt the column width or
row height to fit the text of cells.
Methods:
procedure AutoSizeCol(Col: integer);
Adapts the width of column Col to have all text in cells in this column fit.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
98 | P a g e
procedure AutoSizeColumns(DoFixedCols: Boolean; Padding: integer);
Adapts the width of all columns (including fixed columns when DoFixedCols = true) to the width of
the text. An additional parameter Padding can be used to add some extra padding width to the
column’s width.
procedure AutoGrowCol(Col: integer);
Adapts the width of column Col to have all text in cells in this column fit. The width of the column
can only increase when the text is too large, it will never shrink.
procedure AutoGrowColumns(DoFixedCols: Boolean; Padding: integer);
Adapts the width of all columns (including fixed columns when DoFixedCols = true) to the width of
the text. An additional parameter Padding can be used to add some extra padding width to the
column’s width. Equivalent to AutoGrowCol(), the width of the column can only increase when the
text is larger than the column width. The width will never decrease though when calling
AutoGrowColumns().
procedure AutoFitColumns(DoFixedCols: Boolean = true);
Changes the width of all columns proportionally to ensure all columns fill the entire width of the
grid. When DoFixedCols = false, the size of the fixed columns is not affected, only the size of the
normal columns is proportionally changed.
procedure AutoSizeRow(Row: integer);
Adapts the height of row Row to have all text in cells in this row fit.
procedure AutoSizeRows(DoFixedRows: Boolean; Padding: integer);
Adapts the height of all rows (including fixed rows when DoFixedRows = true) to the height of the
text. An additional parameter Padding can be used to add some extra padding width to the row’s
height.
procedure AutoNumberCol(Col: integer);
Fills the rows of a column with a series of numbers, incrementing from first row to total number of
rows. The grid public property AutoNumberOffset sets the value of the first row and the property
AutoNumberStart sets the first row index from where auto numbering should be applied.
procedure AutoNumberRow(Row: integer);
Fills the columns of a row with a series of numbers, incrementing from first column to total number
of columns. The grid public property AutoNumberOffset sets the value of the first column and the
property AutoNumberStart sets the first column index from where auto numbering should be
applied.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
99 | P a g e
TAdvStringGrid row hover buttons
With TAdvStringGrid it is possible to have a series of buttons automatically hover over the active
row of the grid. This customizable series of buttons can be used for some quick actions such as
clearing the row, inserting preset values etc…
The feature is exposed via grid.HoverButtons that has following properties:
grid.HoverButtons.Buttons: THoverButtonsCollection : collection of buttons
grid.HoverButtons.Column: integer : sets the column where the hover buttons should appear
grid.HoverButtons.Enabled: Boolean : set true to enable this feature
grid.HoverButtons.Position: position where the buttons should be displayed in the selection column
grid.HoverButtons.Rows: selects whether the hover buttons appear for normal rows only or both
normal & fixed rows.
A button on the hover buttons can have:
THoverButton.Caption: string : caption of the button
THoverButton.Enabled: Boolean : enabled state of the button
THoverButton.Flat: Boolean : selects between regular & flat button style
THoverButton.Hint: string : sets the hint for the button
THoverButton.ImageIndex: integer : sets the image from the grid.GridImages imagelist to use on the
button.
THoverButton.Picture: TPicture : sets a picture for use on the hover button
THoverButton.Tag: integer
Below is a sample where 3 hover buttons were added via grid.HoverButtons.Buttons and a PNG
image was set on each button. The grid.HoverButtons.Column was set to column 4, so the
hoverbuttons appear on the row where the mouse hovers on the left side of column 4.
When a hover button is clicked, the event OnHoverButtonClick is triggered, returning the row where
the action happened as well as the button that triggered it.
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
100 | P a g e
TAdvStringGrid nodes
A multi-level hierarchy row expand/contract functionality can be added to TAdvStringGrid through
Nodes. Working with nodes involves three topics:
putting nodes in the grid
node appearance
reacting to node click events
Following functions are available to work with nodes in the grid:
procedure AddNode(aRow,Span:integer);
Adds a node in the grid spanning Span rows
procedure RemoveNode(aRow:integer);
Removes a node at row aRow.
function IsNode(aRow:integer):boolean;
Returns true if the row contains a node
function GetNodeState(ARow:integer):boolean;
Returns true if the node is in contracted state
procedure SetNodeState(ARow:integer;value:boolean);
Sets the state of node
procedure ExpandNode(ARow:integer);
Expands the node at row ARow.
procedure ContractNode(ARow:integer);
Contracts the node at row ARow
procedure ExpandAll;
Expands all nodes
procedure ContractAll;
Contracts all nodes
function GetNodeSpan(aRow: Integer): Integer:
Retrieves the number of rows a node spans
function GetNodeLevel(aRow: Integer): Integer;
Retrieves the depth level of a node
function GetParentRow(aRow: Integer): Integer;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
101 | P a g e
Returns the index of the parent row of any given row. If the row is not a child of a node, -1 is
returned.
procedure InsertChildRow(ARow: Integer);
Inserts a new row within the span of a node
procedure RemoveChildRow(ARow: Integer);
Removes a child row from a node
Everything starts by adding a node to a grid and this is done with the AddNode method. The first
parameter is what we call the visible row position in the grid where you want to add a node. When
working with hidden rows, there is a difference between visible row position and real row position
which takes the hidden rows into account. (Whenever you wan to map the visible row position to a
real row position, use the RealRowIndex method) The second parameter in the AddNode method is
the span of the node, that is, the number of rows to expand or contract when clicking this node. If
this span parameter is zero, the node will automatically expand or contract to the next found node
in the grid.
The RemoveNode and IsNode methods are simply doing what their names refer to. Also notice in this
case, that the row refers to the visible row position!
With these function, you can start adding simple row expand/contract functionality to your grid. In
the example procedure below, nodes are inserted to allow expansion or contracting of equal cells in
column 1:
var
i,j:integer;
begin
with advstringgrid1 do
begin
I := 1;
J := 1;
while (I < RowCount - 1) do
begin
while (Cells[1,J] = Cells[1,J + 1]) and (J < RowCount - 1) do
Inc(j);
if (I <> J) then
AddNode(I,J I + 1);
I := J + 1;
J := I;
end;
Row := 1;
Col := 1;
end;
end;
In order to programmatically expand or contract nodes, either the function GetNodeState,
SetNodeState or ExpandNode and ContractNode are available. The difference is the used row
mapping. GetNodeState and SetNodeState work with this visible row index, while ExpandNode and
ContractNode work with the real row index. Often, you will want to maintain the exact real row
position of the node to expand and use the ExpandNode or ContractNode method. This is because
the visible row position can change all the time by user interaction, while the real row position is
under program control:
procedure TForm1.Button3Click(Sender: TObject);
begin
AdvStringGrid1.ExpandNode(RealRow);
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
102 | P a g e
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
AdvStringGrid1.ContractNode(RealRow);
end;
A second topic involved in using nodes, is the node appearance. Nodes always appear in the first
column (index 0) and can be one of 4 types : cnflat, cn3D, cnglyph or cnXP. A flat node is simply a
rectangle with the well known + / - sign in it. The 3D node type is a raised or sunken rectangle
while you can also specify your own glyph for the expand or contract state. The appearance of the
node is controlled through the CellNode property of TAdvStringGrid. You can speficy here the glyphs
as well as the color of the flat and 3D node.
Further properties of CellNode are:
ShowTree: Boolean; when true, a tree connecting the nodes is drawn
ShowTreeFull: Boolean; when true, a tree is draw horizontally till the right side of the cell
TreeColor: TColor; sets the color of the tree lines.
Multilevel nodes
TAdvStringGrid supports multi level nodes. This is done by inserting nodes within the span of an
existing (parent) node. It is required that the span of a child node is within the span of the parent
node. If this is not the case, the multi-level node setup is incorrect and will not work properly. The
above node scheme is obtained by following code:
advstringgrid1.AutoNumberCol(1);
advstringgrid1.AddNode(1,10); // main node
advstringgrid1.AddNode(3,2); // child node 1
advstringgrid1.AddNode(5,5); // child node 2
advstringgrid1.AddNode(6,2); // child node of child node 2
Last but not least, four event handlers give feedback on user node expansion or contraction through
the OnExpandNode, OnContractNode and OnBeforeExpandNode and OnBeforeContractNode events.
For the OnExpandNode, OnContractNode, two additional parameters come with this event handler:
the visible row index of the node clicked as well as the real row index of this node:
procedure TForm1.AdvStringGrid1ExpandNode(Sender: TObject; ARow,
ARowReal: Integer);
begin
ShowMessage(‘Expand : ' + IntToStr(ARow) + '-' + IntToStr(ARowReal));
end;
TMS SOFTWARE
TADVSTRINGGRID
DEVELOPERS GUIDE
103 | P a g e
For the OnBeforeExpandNode and OnBeforeContractNode and additional parameter Allow by
reference is available with which it can be dynamically controlled whether the node can
contract/expand or not.
TAdvStringGrid filtering
Basic filtering
With the filtering capabilities in TAdvStringGrid, showing only a filtered set of rows in the grid is
easy. Two properties are used for filtering. First there is the FilterData property, which is a
TCollection of filter conditions for each column and second is the property FilterActive through
which filtering is performed when set true.
Taking a closer look at the FilterData collection, this is a TCollection of elements with following
properties:
Column: Integer; integer value, setting the column for which to apply the filter condition
Condition: string; this is a string setting the filtering condition
CaseSensitive: Boolean; sets whether the filter is case sensitive or not
Data: TFilterCells: controls what specific cell data the filter should apply to (see below)
Suffix: string; sets the suffix string to ignore for the filtering condition
Prefix: string; sets the prefix string to ignore for the filtering condition
Operation: TFilterOperation; sets the logical operation between multiple filters
Method: TFilterMethod: when set to default value fmExpression, the condition is treated as an
expression that can contain wildchars like *,?,!,>,<. When it is set to fmLiteral, a direct string
comparison will be done between condition and cell content, i.e. a special symbol like ‘*’ will not
be treated as wildchar.
RemoveAccented: Boolean; when this is set to true, the filtering ignores accented characters. This