0% found this document useful (0 votes)
1K views

EhLib Users Guide

This document provides an overview and instructions for using components from the EhLib library, including the enhanced TDBGridEh grid component, TPrintDBGridEh printing component, TDBSumList summary component, and data-aware edit controls. It also covers the TMemTableEh in-memory dataset component and TDataDriverEh data access component.

Uploaded by

Andre Cravo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

EhLib Users Guide

This document provides an overview and instructions for using components from the EhLib library, including the enhanced TDBGridEh grid component, TPrintDBGridEh printing component, TDBSumList summary component, and data-aware edit controls. It also covers the TMemTableEh in-memory dataset component and TDataDriverEh data access component.

Uploaded by

Andre Cravo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 52

Library of Components – EhLib 5

Developer’s guide

EhLib Team
2012
Edition: 1.53
(Changes and additions are
highlighted in red color)
Introduction...............................................................................................................4
Installation.................................................................................................................7
Unpacking archive........................................................................................................................7
Installing packages.......................................................................................................................8
Installing help files.......................................................................................................................9
Using TDBGridEh component................................................................................10
Brief description of TDBGridEh, TDataLink and TDataSet......................................................10
Working with TDBGridEh at design-time.................................................................................10
Panel of detail information for record – RowDetailPanel..........................................................11
RowPanel mode..........................................................................................................................12
Working with data in grouping mode.........................................................................................12
TDBGridEh and vertical scrollbar..............................................................................................15
Customizing scrollbars...............................................................................................................15
Using DBGridEh for sorting and filtering data in the DataSet..................................................15
Customizing grid title.................................................................................................................19
Customizing Indicator column...................................................................................................19
Customizing grid footer..............................................................................................................20
Customizing grid cells................................................................................................................20
Hints and Tooltips.......................................................................................................................23
Customizing in place editor in grid cell.....................................................................................23
Automatically fits the width of the grid columns to the width of the grid client area...............24
3D and flat look..........................................................................................................................24
Drawing information about the absence of records in a dataset.................................................24
Using properties of TDBGridEh.IndicatorTitle.........................................................................24
Using global properties for TDBGridEh....................................................................................25
Import/Export TDBGridEh data to/from various formats..........................................................28
Other features.............................................................................................................................28
Converting existing TDBGrid component to TDBGridEh........................................................29
Using TPrintDBGridEh component........................................................................30
Rich text before and after grid....................................................................................................30
Features that current version of TPrintDBGridEh is not supported...........................................30
FAQ List:....................................................................................................................................30
Using TDBSumList component..............................................................................31
Common understanding of TDBSumList...................................................................................31
How it works and why SumList sometimes calculate aggregation values incorrectly..............31
Using data-aware edit controls................................................................................32
Common understanding of edit controls....................................................................................32
Working with edit buttons..........................................................................................................32
Using TDBDateTimeEditEh control..........................................................................................32
Using TDBNumberEditEh control.............................................................................................33
Using TDBComboBoxEh control..............................................................................................33
Using TDBLookupComboboxEh control..................................................................................33
Using SpecRow in columns of DBGridEh component and in DBLookupComboBoxEh
component..................................................................................................................................34
Using TPropStorageEh and TPropStorageManagerEh components.......................35
Introduction in technology of interaction between MemTable and DataDriver......36
TMemTableEh component......................................................................................37
Two working mode of TMemTableEh component....................................................................37
ViewScroll..................................................................................................................................37
Master/detail relations................................................................................................................37
Storing records in tree mode (TreeView)...................................................................................37
Working with AutoIncrement fields...........................................................................................38
Using indexes.............................................................................................................................39
Using shared array of records by several TMemTableEh’s........................................................39
TRefObjectField field type.........................................................................................................39
Using maintained aggregates.....................................................................................................39
Records sorting...........................................................................................................................39
Creation/removing table data in memory in the ‘stand-alone’ mode.........................................40
Working with MemTableEh in the 'with datadriver' mode.........................................................40
Cached updates...........................................................................................................................41
Marking and Returning to Records............................................................................................41
Searching in TMemTableEh.......................................................................................................42
Quick access to the record values...............................................................................................44
Internal objects of TMemTableEh component...........................................................................45
Workig with TMemTableEh at design-time...............................................................................45
TDataDriverEh component.....................................................................................46
TSQLDataDriverEh component..............................................................................47
TSQLDataDriverEh or TXXXDataDriverEh, which one is best to use...................................50
Working with TSQLDataDriverEh and TXXXDataDriverEh at design-time..........................50
Feedbacks and bug reports......................................................................................51
Anotações Alt_C......................................................................................................51
Introduction
The Library contains components and classes for Borland Delphi versions 5, 6, 7, 8 & 2005 and
Borland C++ Builder versions 5 & 6, Borland Developer Studio 2006, CodeGear Delphi 2007,
RAD Studio 2009, Embarcadero RAD Studio 2010, RAD Studio XE & RAD Studio XE2. The
Library is intended to increase capacity of the client’s part of the database application by
improving interaction between application and users.

TDBGridEh component Using TDBGridEh


It provides all functionality of TDBGrid and adds several new features as follows:
- Allows to select records, columns and rectangle areas.
- Provides special titles that can cover several or all columns.
- Can have a footer that is able to show sum/count/other field values.
- Allows to resize column automatically to fit grid width equal to client width.
- Has an ability to change row height and title height.
- Allows automatic broken of a single line long title and data rows to a multiline.
- Allows title to act as button and, optionally show a sort marker.
- Allows to mark titles by sortmarking sings automatically and sort data in DataSet.
- Allows to truncate long text with ellipsis in cells.
- Allows lookup list to show several fields.
- Have an ability to make an incremental search in lookup fields.
- Can have frozen nonscrollable columns.
- Allows to show DateTime picker for TDateField and TDateTimeField.
- Allows to show bitmaps from TImageList depending on field value.
- Allows to hide and track horizontal or vertical scrollbars.
- Allows to hide columns.
- Allows to show 3D frame for frozen, footer and data rows.
- Allows to draw memo fields.
- Can show multiline inplace editor.
- Can have a proportional scrolling for DadaSets independently of dataset’s sequencing.
- Allows to show checkboxes automatically for Boolean fields. Allows to show checkboxes
for other type of fields.
- Has procedures to save and restore layout (visible columns, columns order, columns width,
sortmarkers, row height) in/from registry or ini file.
- Allows to show hint (ToolTips) for text that don't fit in the cell.
- Allows to export data to Text, Csv, HTML, RTF, XLS and internal formats.
- Allows to import data from Text and internal formats.
- Can sort data in various datasets.
- Can filter data in various datasets.

TDBLookupComboboxEh component Using edit controls


It provides all functionality of TDBLookupCombobox and adds several new features as follows:
- Can have flat style.
- Allows to assign values as to KeyValue property and as to display Text property.
- Allows to hold KeyValue and Text that will not affect to each others values.
Drop down list can:
- Show titles,
- Have sizing grip,
- Automatically set width as sum of DisplayWidth of the list fields (Width = -1),
- Automatically drops when the user pressed the key.
- Can have specified width.
Edit button can:
- Show DropDown and Ellipsis or Bitmap image.
Have additional events: OnKeyValueChanged and OnButtonClick.

TDBSumList component Using TDBSumList


It is intended for calculating sums and amount of records in a TDataSet with dynamic changes.
Component keeps a list of TDBSum objects, which contains types of group operations (goSum
or goCount) and name of fields which values need some calculation. (goCount name of field is
unnecessary).

TPrintDBGridEh component Using TPrintDBGridEh


TPrintDBGridEh provides properties and routines for preview and print of TDBGridEh
component with several features:
- Ability to expand rows vertically until all text is printed.
- Ability to scale grid to fit it to the page width.
- Ability to print/preview title for grid.
- Ability to print/preview page header and page footer where you can specify macros for
current page, current date, current time and/or static text.
- Automatically print/preview multi-selected area of TDBGridEh if it’s area is not empty.
- Ability to print/preview rich text before and after grid.

TPreviewBox component
TPreviewBox lets you to create a customizable runtime preview.

TPrinterPreview object
TPrinterPreview lets you to record printable data in buffer for following output them on screen
and to printer. TPrinterPreview have all functions and properties as in TPrinter object. You can
use TPrinterPreview object similarly to TPrinter except some details. In TPrinter
Printer.Canvas.Handle and Printer.Handle is the same but in TPrinterPreview
PrinterPreview.Canvas.Handle represents the metafile in that is recored the data and
PrinterPreview.Handle represents Printer.Handle. It means that you have to use
PrinterPreview.Canvas.Handle for drawing operation (like DrawText, DrawTexteEx, e.t.c.) and
use PrinterPreview.Handle for such functions as returning information about printer facilities
(GetDeviceCaps, e.t.c.). Global function PrinterPreview returns default PrinterPreview object
and shows data in the default preview form.

TDBEditEh component Using edit controls


represents a single or multi-line edit control that can display and edit data of field in a dataset or
can work as non data-aware edit control.

TDBDateTimeEditEh component Using edit controls


represents a single-line date or time edit control that can display and edit data of TDateTime
fields in dataset or can work as a non data-aware edit control.

TDBComboBoxEh component Using edit controls


represents a single or multi-line edit control that combines an edit box with a scrollable list and
can display and edit a field in a dataset or can works as non data-aware combo edit control.

TDBNumberEditEh component Using edit controls


represents a single-line number edit control that can display and edit a numeric field in a dataset
or can work as non data-aware edit control.

TPropStorageEh, TIniPropStorageManEh, TRegPropStorageManEh components


Using TPropStorageEh
These components realize a technology of storing component properties to/from such storages as
INI files, Registry etc.

TMemTableEh component
It is a dataset that holds all data in memory and can get data from TDataDriverEh and return
changed records back to the TDataDriverEh.

TDataDriverEh component
Deliver records from the server to the TMemTableEh.
Deliver changed records from TMemTableEh back to the server.

TDataSetDriverEh component
It is a DataDriver that deliver records in TMemTableEh from other DataSet and deliver changed
records from TMemTableEh back to the DataSet.

TSQLDataDriverEh component
It is a DataDriver that have properties for keeping five SQL expressions and parameters for
querying data, removing, insertions, updating and refreshing records. TSQLDataDriverEh by
itself can’t request data from server, but it can prepare parameters of the request and have a
global event that programmer can write for transferring SQL expression to/from the server.

TBDEDataDriverEh component

It is a DataDriver that interacts with the DB server using BDE connection.

TIBXDataDriverEh component
It is a DataDriver that interacts with the DB server using IBX connection.

TDBXDataDriverEh component
It is a DataDriver that interacts with the DB server using DBX connection.

TADODataDriverEh component
It is a DataDriver that interacts with the DB server using ADO connection.
Installation
Below it will be described how to install EhLib under Delphi 6.
Uninstall previous or evaluation version of EhLib from Delphi 6 IDE.
Remove or copy this files to other directory this files to prevent crossing this and new version of
EhLib (Including EhLib.bpl, EhLib.dcp, EhLibXX.bpl, EhLibXX.dcp files).

Unpacking archive
Unpack EhLib archive.
After unpacking you will have next list of directories:

Directories of 'EhLib - source include' version:

BCB5 Contain source files which are specific for C++ Builder 5.
BCB6 Contain source files which are specific for C++ Builder 6.
Common Contain source files which are common for all versions of Delphi and C++
Builder.

Delphi5 Contain source files which are specific for Delphi 5.


Delphi6 Contain source files which are specific for Delphi 6.
Delphi7 Contain source files which are specific for Delphi 7.
DEMOS Demonstration projects. It use tables from the DEMOS directory and BDE
alias "DBDEMOS".
LangResources Contain resource files for various languages.
DataService Contain files that contain objects that allows to sort data in various types of
datasets.
ORDERS Contain text files in which described how to register various versions of
EhLib.
HLP Contain help files.

Directories of 'Ehlib - without source' version or 'Ehlib- Evaluation version':

BCB5 Contain all binary files which are need for C++ Builder 5.
BCB6 Contain all binary files which are need for C++ Builder 6.
Common Contain interface part of source files of EhLib. (Only for information, not
require for installation.)

Delphi5 Contain all binary files which are need for Delphi 5.
Delphi6 Contain all binary files which are need for Delphi 6.
Delphi7 Contain all binary files which are need for Delphi 7.
DEMOS Demonstration projects. It use tables from the DEMOS directory and BDE
alias "DBDEMOS".
LangResources Contain resource files for various languages.
DataService Contain files that contain objects that allows to sort data in various types of
datasets.
ORDERS Contain text files in which described how to register various versions of
EhLib.
HLP Contain help files.
Create, if need, new directory "EhLib" in your Delphi_X directory. (For instance:
C:\Delphi6\EhLib).
If you have EhLib - source include version then copy to this directory files from Common and
Delphi6 directory of EhLib archive.
If you have EhLib - without source version or evaluation version EhLib then copy to this
directory files from Delphi6 directory of EhLib archive.
By default EhLib contains resource for English language. If you need other languages you can
replace original resource files (which already present in C:\Delphi6\EhLib) by the files that is
placed in corresponding language directory.
If you don't find found directory for necessary language then you need to take files from any
existing language directory and change it as you need.

Installing packages.
Automatic installing:
Run Installer\EhLibInstaller.exe program from EhLib archive to install library in Delphi/C++
Builder IDE automatically. In time of installation the program creates folder, copies files,
compile required packages and registers packages in the IDE.

Manual installing:
Run Delphi and use "File\Open..." menu item of Delphi IDE to open the EhLib runtime package
C:\Delphi6\EhLib\EhLib60.dpk. In "Package..." window click "Compile" button to compile and
build bpl file.
By default Delphi place compiled EhLib60.BPL file to the <Delphi path>\Projects\Bpl directory
and this directory already present in the search PATH. But if you overwrite default BPL directory
then you need to put the compiled EhLib60.BPL file into directory that is accessible through the
search PATH (i.e. DOS "PATH" environment variable; for example, in the Windows\System
directory).
After compiling run-time package you must install design-time package DclEhLib60.BPL into
the IDE.
Use "File\Open..." menu item to open design-time package DclEhLib60.dpk. In "Package..."
window click "Compile" button to compile the package and then click "Install" button to register
EhLib components on the component palette.
EhLib components have to appear on 'EhLib' page of components palette.

Instalation note for users who had EhLib 1.X or 2.X:

Note that Delphi IDE does not move components to the new default place on components palette
when you install new version of same component(s). So if you already have EhLib installed, then
after installation new version does not move EhLib components to the 'EhLib' page. To force
Delphi IDE to move components to the default place on components palette do next:
Open menu: Component->Configure Palette.
Select '[All]' line in Pages listbox.
Click 'Default Pages' button.
Add, (if need) EhLib directory ("C:\Delphi6\EhLib") in Tools->Environment Options->Library-
> Library Path.
Troubleshooting.

Problem: Solution:
In compilation time 1. It can be because Delphi have access to units from old version of
Delphi shows next error: EhLib. Try to remove old version of EhLib completely.
"Unit AAA compiled 2. It can be because your Delphi or C++ Builder Build number is not
with different version of equal to Delphi or C++ Builder Build number under which EhLib
unit BBB" was compiled. See Build number of Delphi and C++ Builder under
which EhLib was compiled below:

C++ Builder 5 (Build 12.34) Update Pack 1

Delphi 5 (Build 6.18) Update Pack 1

Delphi 6 (Build 6.163)


[Fatal Error] It can be, because you did not copy files from Common and Delphi6
EhLib.dpk(51): File not directories of EhLib archive to the one directory.
found: 'DBSumLst.dcu' If you have EhLib - source include version then copy files from
Common and Delphi6 directory of EhLib archive to alone directory.

Installing help files.


Copy EhLib.hlp and EhLib.cnt files from HLP directory of EhLib archive to the Delphi 6 HELP
subdirectory.
Run Delphi IDE.
Select Help|Customize menu to start the OpenHelp application.
Add the EhLib.cnt file to the Contents page, add the EhLib.hlp file to the Index and Link pages.
Select "File->Save Project" menu.
Close OpenHelp application.
To check that EhLib help files have been installed correctly, drop DBGridEh component on the
form and press F1. Delphi IDE have to open help window with information about TDBGridEh
component.
If you want to install help files under several Delphi versions simultaneously (or under C++
Builder and Delphi simultaneously) then you have to create a copy of EhLib.hlp and EhLib.cnt
for every version of Delphi or C++ Builder with individual files name (For instance for Delphi 6
copy files EhLib.hlp andEhLib.cnt to EhLibD6.hlp and EhLibD6.cnt respectively).
Next - need to edit file EhLibD6.cnt. This file contain several ":Include" clause at first lines.
Comment (using semicolon sign) lines that don’t contain DELPHI6.OHL word)
:BASE EhLib.hlp
:TITLE EhLib library
;:Include bcb4.cfg
;:Include bcb5.ohl
;:Include delphi4.cfg
;:Include DELPHI5.OHL
:Include DELPHI6.OHL.
Copy EhLibD6.hlp and EhLibD6.cnt to Delphi 6 HELP subdirectory and install help files as
described above.
Using TDBGridEh component
Brief description of TDBGridEh, TDataLink and TDataSet.
All below texts are equally pertained in both TDBGridEh component and TDBGrid component.
A TDBGridEh control lets you to view and to edit records in a dataset as a tabular grid format.
TDBGridEh does not store data in itself, it only show data from dataset via TDataLink object.
Every database control have internal TDataLink object to interact with dataset. You can connect
TDBGridEh to dataset using DataSource property. If you already have used TStringGrid
component you can see that data shows in TStringGrid and in TDBGridEh very similarly, but
mechanism that uses to show data in TStringGrid and in TDBGridEh are very different. In
TStringGrid count of rows is equal to rows in array of strings, while in TDBGridEh (and
TDBGrid) count of rows always not more than count of visible rows and although vertical
scrollbar can display thumb position regarding the count of record in dataset, In reality, it take
information not from grid but directly from dataset. TDataSet doesn't allow us to work with data
as with array of data i.e. we can not quickly get value of the field from certain record. Some
types of datasets have not even such notion as record number (in such datasets we can only know
what we are at the beginning of dataset or at the end of it or somewhere between them. In that
case DBGrid shows vertical scrollbar only in three positions). But to have possibility to draw
several records simultaneously, TDataLink object allows having buffer of records (record buffer
window) for quick random access. DBGrid uses this possibility of datalink and it sets size of
record buffer window equal to count of visible rows in the grid. We can not control what record
must be first in this buffer, DataLink itself scrolls record buffer window when we navigate
through the dataset. And it controls the scrolling of record buffer window so that the active
record is always in the record buffer window. It is a reason why the active record changes
position when users change thumb position of vertical scrollbar using mouse.

Working with TDBGridEh at design-time.


TDBGridEh contains rows and columns. Every row is a record in TDataSet. Every column is a
field in TDataSet. Columns can be dynamic or static. Dynamic columns are recreated every time
when the state of DataSet is changed. State of DataSet can be changed in several cases. It is
changed when, for example, DataSet is reopened. When column is
recreated, values of column properties are reset to their default
values. It is useful to use dynamic columns when the list of fields of
DataSet is not known in advance. In the mode of static columns grid
itself never recreates columns. At design-time to create static
columns you need to double-click on the grid. The Columns Editor
window will be open. Press “Add all fields” in this window. Grid
will create static column for every DataSet field.
To customize properties of column you need to select its name in the The Columns Editor
window. You can also select column in Object Inspector by clicking column title in the grid. If
grid is connected to DataSource and
DataSource is placed on the same
Form as grid, then icon of
DataSource will be shown in the
bottom right corner of the Grid. You
can click on the DataSource icon to
select DataSource in Object
Inspector. In same manner grid can
show DataSet. If a DataSet is a
TMemTableEh then grid also can show TDataDriver and DataSet which is connected to
DataDriver as a ProviderDataSet.

Panel of detail information for record – RowDetailPanel.


Sub properties of RowDetailPanel property allow you to create and customize the panel of
detailed information for grid rows.
Panel if detailed information is a
special area inside grid where you
can put any control from
Component Palette on it. At design-
time a panel is always opened under
the current record. At run-time panel
is hidden, and there is a ‘+’ sign at
the beginning part of every row. You
can click ‘+’ sign to open panel. At
once time panel can be opened only
for one row. You can also open
panel using key combination Ctrl-
Down or key ‘+’. Use Ctrl-Up to
return from panel to grid row. Use
‘*’ key to show or hide panel
depending on current state.

Subproperties of RowDatailPanel propery:


Active: Boolean; this propery allows activating panel of detailed information.
Width: Integer; width of panel
Height: Integer; height of panel
ActiveControl: TWinControl; use this property to define control which will be focused
when panel is opening.
BevelEdges: TBevelEdges, BevelInner: TBevelCut, BevelOuter:
TBevelCut, BevelKind: TBevelKind, BevelWidth:
TBevelWidth, BorderStyle: TBorderStyle: Use these properties to
control border style of panel.
Color: TColor; Color of panel
ParentColor: Boolean Property defines if it is need to use color of grid as a color
of panel.

Public
Visible: Boolean This property defines if panel is visible. You can set this property at
run-time for reading and writing.

Use event OnCheckRowHaveDetailPanel to control of panel showing in grid. You can set
parameter RowHaveDetailPanel to allow or forbid panel for required record.

Use events OnRowDetailPanelHide and OnRowDetailPanelShow to execute special action after


panel is hidden or before panel is openened.
RowPanel mode.
Grid can work in special mode when every cell of grid can be placed under each other and can
have individual height. Set
RowPanel.Active to True
value to activate this mode.
At design-time you can
place cell, vertical and
horizontal size. At run-time
the possibility to change
position of cell depends on
the presence
dghColumnMove value in
OptionsEh property.
Possibility to change
vertical size of cell depends
on RowSizingAllowed
property.

When user change cell width, the grid also changes width of adjoined cells which are placed
under or above of changing cell and if the right border of these cells match. By analogy when
user changes cell height, grid changes height of cells in left or right part of grid if low borders
march. Press and hold Shift key to change the size of only single cell.
To change cell height of cell you need to move mouse cursor to the low border of the title cell.
Mouse cursor will change its image from arrow to two arrows with up and down direction. At
this moment press right mouse button and change size.
To change position of cell you need to press right mouse button on the title cell and drag it to the
required place.
Additional subproperies of the RowPanel property:
NavKeysNavigationType: TGridRowPanelNavKeysNavigationTypeEh defines the
order of navigation over cells in the grid when keys Up, Down, Left, Right are pressed.
rpntRowToRowEh - (by default) Keys Up, Down move current cell to next or previouse record of
dataset. Keys Left, Rigth worksas Tab and Shift-Tab.
rpntCellToCellEh - Keys Up, Down move current cell to under or above last position from the
current cell. Keys Left, Rigth move current cell to left or right position from the current cell.

TabNavigationType: TGridRowPanelTabNavigationTypeEh defines an order of going


through cells of the grid by Tab key
rpntUpToDownPriorityEh Go, at first, from top to bottom, than from left to right.
rpntLeftToRightPriorityEh Go, at first, from left to right, than from top to bottom.

Working with data in grouping mode.


Grid allows to group data in memory using columns as a grouping criterions.
You can create and change
grouping at design-time and at
run-time.
The grouping works only when
grid is connected to dataset of
TMemTableEh type.
When grid group data it also sort
data in MemTableEh to have
correspondence of data in the gtid
and in the MemTable. The Grid
track data in the MemTable and
moves records in corresponding
groups when data are changed.
Use subproperties of
Grid.DataGrouping property to
control grouping. Use
Grid.DataGrouping.GroupLevels
property to create structure of
grouping. GroupLevels is a
collection of
TDBGridEhDataGroupLevelEh.
Every item of collection
corresponds one level of grouping. The key property of the item of collection is the
ColumnName property of String type. This property keeps name of the column of field for
which the records will be group. Use TColumnEh.Name property to get the name of the column
at run-time. Use Font and Color properties of structures’ items to control the format of the
grouping records. Set Grid.DataGrouping.Active to True to activate the grouping. Set
GroupPanelVisible property to True to show the current active structure of the grouping. Special
panel will be shown with active items of grouping at the top part of the gird. The element of the
grouping collection is active when its ColumnName property holds a name of a column. After
activation of grouping panel, you can make and change the grouping structure using drag-n-drop
operations. Drag the column title to the grouping panel to group data by this column. In time of
forming the tree of grouping, grid creates the new group record when the value of the field of
column Column.Field is changed. You can change key value of grouping in the event
TDBGridEhDataGroupLevelEh.OnGetKeyValue or TColumnsEh.OnGroupGetKeyValue. Take
current value of the key value from the field GroupLevel.Column.Field.Value. Write the changed
value to the KeyValue parameter of the event procedure.
For example, next event will form tree of grouping that will have only two grouping records ‘Big’ and ‘Small’ for
numeric field that have record values that bigger or smaller them 100.
procedure TForm1.gridFishColumns6GroupGetKeyValue(Sender: TCustomDBGridEh;
Column: TColumnEh; var KeyValue: Variant);
begin
if Column.Field.AsFloat > 100 then
KeyValue := 'Big'
else
KeyValue := 'Small';
end;

Grid uses key value to form string that will be shown in the grouping row. If you changed key
value of the grouping, then you likely need to change algorithm that convert key value to display
value for display. Write OnGetKeyValueAsText event to do it. Write
Grid.OnDataGroupGetRowText and GroupLevels.OnGetGroupRowText to rewrite the algorithm
of forming the text that is shown in the grouping row.

Use property Grid.DataGrouping.GroupDataTree to access the items of grouping tree. The


property have the TGridGroupDataTreeEh type and is inherited form TTreeListEh. The itmes of
TTreeListEh class form the tree-type structure of groups and references to DataSet records for
the lowest levels of grouping. Use properties FlatVisibleCount and FlatVisibleItem[Index] to
access items as a flat list. The flat list FlatVisibleItem contain only items which are in the scope
of the expanded nodes. Amount of items in flat array corresponds amount of rows in the grid.
Every item of array is a reference to the instance of TGroupDataTreeNodeEh class and defines a
node in the grouping tree. Basic properties of this class are:
Count: Integer; Amount of nodes in the group. Nodes can be over groups of lower level or
references to dataset records.
DataGroup: TGridDataGroupLevelEh Reference to item of grouping structure. Not empty if
the node is a node of group.
DataSetRecordViewNo: Integer. Number of record in MemTableEh. Not empty if the node is a
node of the dataset record.
Expanded: Boolean. Noe is expanded.
Items[Index: Integer]: TGroupDataTreeNodeEh. List of nodes of the lower level.
KeyValue: Variant;
Level: Integer The number of node level;
NodeType: TGroupDataTreeNodeTypeEh. Type of the node. The Node of a group level or a record
level.
Parent. Указатель на родительскую ветку верхнего уровня.

Use Items property of Grid.DataGrouping.GroupDataTree to access the grouping tree as a tree-


type structure. Every item of this list is a reference to a tree node of grouping of highest level.

Grid.DataGrouping property has next subproperties:


Active: Boolean – Set this property to active grouping in the grid.
DefaultStateExpanded: Boolean – Define Expanded state for every new group node.
GroupLevels: TGridDataGroupLevelsEh – Collection of the grouping structure. Use this property
to define template of grouping.
GroupPanelVisible: Boolean – Set this property to True to show panel of grouping in the top part of
the grid. When the panel is visible you can form the structure of grouping by dragging the title of the
column onto this panel.
Font: TFont – Defines default Font of grouping records.
Color: TColor - Defines default Color of grouping records.

Write Grid.OnActiveGroupingStructChanged to take action when the structure of grouping is


changed.

Grid calls OnDataGroupGetRowParams before drawing of a group record.


In the event you can change Text, Color,
Font and add Image from ImageList on
the left of the text.
When the event is calling the DataSet is
positioned on the first record in the
group. So you can access field values of Dataset inside the event.

The event has next type and declaration:

TDBGridEhDataGroupGetGroupRowParamsEvent = procedure ( Sender:


TCustomDBGridEh; GroupDataTreeNode: TGroupDataTreeNodeEh; Params:
TGroupRowParamsEh) of object;

TGroupRowParamsEh type has next properties:


property Color: TColor; // Color of the cell background
property Font: TFont; // Font of the text
property Images: TCustomImageList; // ImageList to show images
property ImageIndex: Integer; // Index of a image from the ImageList.
property GroupRowText: String; // Text to show in the cell of the group
property State: TGridDrawState; // Readonly property. Draw state.

TDBGridEh and vertical scrollbar.


If you work with different types of dataset you can notice that for some types of dataset the
DBGrid shows vertical scrollbar correctly, but for other dataset their vertical scrollbar has only
three positions independently of record count in dataset. To adjust the vertical scrollbar
accommodation the DBGrid uses RecordCount and RecNo property of DataSet component. But
some dataset holds -1 in RecordCount and RecNo. DataSet function IsSequenced indicates
whether the underlying database table uses record numbers to indicate the order of records.
When IsSequenced returns True value, applications can safely use the RecNo property to
navigate through records in the dataset and DBGrid can use RecNo property to show thumb
position in vertical scrollbar. But when IsSequenced returns False value, DBGrid can not define
current record position and it shows vertical scrollbar in three positions. DBGridEh component
has possibility to show proportional scrollbar for no sequenced dataset. To do it we need to
activate SumList and create list of record bookmars. Set SumList.Active to True and
SumList.VirtualRecords to True. SumList will run through dataset and create list of records
bookmarks. If you use client/sever technology to access database SumList will force dataset to
fetch all records, but this operation can take much time. Keep in mind that VirtualRecords will
work only for full relationship bookmarks dataset, it means that DataSet.ComapreBookmark
function has to return > 0 if record1 is after record2 (i.e. record to which bookmark1 indicates
has to be after record to which bookmark2 indicates). It must return 0 if bookmark1 and
bookmark2 points to the same record, and value < 0 if record1 is before record2. TBDEDataSet
in most cases support full relationship bookmarks.

Customizing scrollbars.
To customize scollbars you need to use subprtoperties of HorzScrollBar and VertScrollBar
properties.
Tracking: Boolean This property …
SmoothStep: Boolean …
ExtScrollBar: TScrollBar; …
Visible: Boolean; …
VisibleMode: TScrollBarVisibleModeEh;
sbAlwaysShowEh Always shows scrollbar.
sbNeverShowEh Never shows scrollbar.
sbAutoShowEh Shows or hides scrollbar automatically
depending on visible area of grid.
If grid is connected to DataSet of TMemTableEh type then on vertical scrolling grid doesn’t
change position of active record.

Using DBGridEh for sorting and filtering data in the DataSet.


DBGridEh can not sort or filter data by itself. But it can pass action for sorting or filtering to the
specal object that will do it in DataSet. You can adjust grid for two types of sorting (local or
server), using property SortLocal and two type of filtering (also, local and server), but real
possibility to apply each type of operation depends on the type of DataSet. For instance,
TBDEDataSet does not suppot sorting locally (inside DataSet). so you can not sort data locally
when grid is linked to TQuery or TTable. Furthermore, EhLib has only special objects for
standard types of DataSet (not for a third party DataSet's).
Below you can see a table of special object and DataSet in which those objects can sort or filter
data.
Unit DataSet Local sorting Server sorting Local filtering Server filtering
EhLibBDE TQuery, N Y Y Y
TTable
EhLibADO TADOQuery, Y Y Y Y
TADODataSet
EhLibCDS TClientDataSet Y Y Y Y
EhLibDBX TSQLQuery, N Y N Y
TSQLDataSet
EhLibIBX TIBQuery, N Y Y Y
TIBDataSet
EhLibMTE TMemTableEh Y Y* Y Y*
* If Grid is configured for Server sorting of Filtering (SortLocal=False, STFilter.Local=False),
then sort operation is transferred to the TMemTableEh.DataDriver object.

When grid is adjusted for a local filtering, the special object will build expression and assign it to
a property Filter of DataSet. So we need also to set Filtered to True value manually.
When grid is adjusted for a server filtering, the special object will build SQL:ORDER BY
expression and it will replace ORDER BY string in SQL or Command property of DataSet and it
will reopen DataSet.
When grid is adjusted for a local sorting, the special object will perform a sorting using
specific type of DataSet.
When the grid is adjusted for a server sorting, the special object will build expression for SQL
'WHERE' clause in SQL string of dataset. It will try to find string that begins from key string
'/*Filter*/' in SQL expression and adds filter expression after this string in same line (You can
change this key string using global variable - SQLFilterMarker) . So your SQL query must have
a line that begins from '/*Filter*/'. For instance:
' select *
from table1
where
/*Filter*/ 1=1 '
For automatically filtering/sorting data in dataset you need to add one of the units EhLibXXX
(EhLibADO, EhLibBDE, EhLibCDS ... depend on the type of dataset where the grid is linked to)
to 'uses' clause of any unit of your project. This units have code to register TDatasetFeaturesEh
based classes (special object) for respective DataSet's. For other third party DataSet's you have to
write and register your own special object or you have to write OnApplyFilter or/and
OnSortMarkingChanged events for every required grid. Moreover, you can write
OnApplySorting and/or OnApplyFilter for the global variable DBGridEhDataService. These
events have TNotifyEvent type where Sender is TCustomDBGridEh.

Adjusting grid for sorting data:

TDBGridEh allows showing special sortmarking bitmaps (small triangles) in the right part of
title cell. In order to automatically mark the title by sortmarking bitmaps you have to add
dghAutoSortMarking to OptionsEh property. Add dghMultiSortMarking to OptionsEh in order to
allow sortmarking in several columns simultaneously. Set Column.Title.TitleButton to true value
for titles which will have possibility to change sortmarkers at run time. Or you can set
ColumnDefValues.Title.TitleButton to allow setting sortmarking for all columns where
Column.Title.TitleButton is not changed. At runtime, clicking on title will change sortmarking.
Holding Ctrl key allows to mark several columns simultaneously. After user changes sormarking
grid will call OnSortMarkingChanged event or will pass action to special object, if it is
registered. Special object will use Grid.SortLocal property to determine how to sort data: locally
or on the server. If you write OnSortMarkingChanged, you can use
TDBGrid.SortMarkedColumns property to access the sortmarked columns and
TColumnEh.Title.SortMarker property to get state of the sortmarker.

Adjusting grid for filtering data:

TDBGridEh allows to show special row (under title) where user enters expressions in cells for
filtering records in dataset.

(Expression in the cell can look like: "1", ">=1", ">1 AND <=5", "%TestStr%"). Set
STFilter.Visible to True value to show this special row. AT Run time, when cursor locate in the
filter cell, they can press ENTER to apply filter. Grid will parse expression in every not empty
filter cell and call TDBGridEh.ApplyFilter. And it calls OnApplyFilter event or passes action to
special object, if it is registered.
For normally parsing, the expression in cell have to have next format:
[Operator1] Operand1 [)] [AND|OR Operator2 Operand2 [)] ]
Where OperatorX is one of [ = | <> | != | > | < | >= | <= | ~ | !~ | in ( ]
OperandX is a numeric, date or string value or for the operator 'IN' it is a list of values divided
by comma.
For instance:
'1'
'>=1'
'>1 AND <=5'
'~ TestStr%'
'!~ TestStr_'
'in (1,2,3,4,5,6) and >100'
'in (Str1,Str2,Str3)'

Grid allows to show dropped down list of STFilter in title cells. Set STFilter.Location to
stflInTitleFilterEh to active this mode. Use item ‘(Custom…)’ to enter string for filtering or press
checkboxes above required values. Global variable DBGridEhShowInTitleFilterBox contain key
combination for opening list of filtering values. By default it contains 'Ctrl-T'.
When grid is connected to the list of uncial values of column is formed automatically. In
addition, list is formed with tacking in account of filter applied in other columns. To form list of
values and command for filtering, use next events and methods: Events -
TDBGridEh.OnFillSTFilterListValues, TColumnEh.OnFillSTFilterListValues,
TDBGridEhCenter.OnFillSTFilterListValues or rewrite method
TDatasetFeaturesEh.FillSTFilterListDataValues and register new class MyDatasetFeaturesEh
for interaction between grid and dataset.

Grid call event OnFillSTFilterListValues every time when it is needed to fill list of StFilter,
that have next type:
TDBGridEhFillSTFilterListValuesEvent = procedure(Sender:
TCustomDBGridEh; Column: TColumnEh; Items: TStrings; var Processed: Boolean)
of object;
This event presents in TDBGridEh, TColumnEh, TDBGridEhCenter.
Every item of Items list must consists of two values: String - Items[i] and Object
Items.Objects[i]. Items of object type must be inherited from TPopupListboxItemEh type and
they must be declared as global variables. There are already next global variables in DBGridEh:
PopupListboxItemEhSortAsc: TPopupListboxItemEhSort;
// Item of the list show sorting item Asc and executes sorting in ascending order.
PopupListboxItemEhSortDes: TPopupListboxItemEhSort;
// Item of the list show sorting item Asc and executes sorting in descending order.
PopupListboxItemEhLine: TPopupListboxItemEhLine;
// Item of the list show horizontal line. On choosing doesn't perform any actions.

PopupListboxItemEhClearFilter: TPopupListboxItemEhSpec;
PopupListboxItemEhAll: TPopupListboxItemEhSpec;
PopupListboxItemEhEmpties: TPopupListboxItemEhSpec;
PopupListboxItemEhNotEmties: TPopupListboxItemEhSpec;
PopupListboxItemEhDialog: TPopupListboxItemEhSpec;
PopupListboxItemEhApplyFilter: TPopupListboxItemEhSpec;

PopupListboxItemEhData: TPopupListboxItemEhData;
// Item of the list shows text that defines text of filtering. When it is selected, it is checked
by checkbox and it is put in the list of items of values that is needed be in the filtered records.

You can call next methods in the event to fill values by default
TDBGridEh.DefaultFillSTFilterListValues(Column: TColumnEh; Items: TStrings)
TDBGridEh.DefaultFillSTFilterListCommandValues(Column: TColumnEh; Items:
TStrings)
TDBGridEh.DefaultFillSTFilterListDataValues (Column: TColumnEh; Items:
TStrings)

Next code show OnSTFilterListValues event where sorting items is deleted from list:
procedure TForm1.DBGridEh1FillSTFilterListValues(Sender: TCustomDBGridEh;
Column: TColumnEh; Items: TStrings; var Processed: Boolean);
var
Index: Integer;
begin
Sender.DefaultFillSTFilterListValues(Column, Items);
Index := Items.IndexOfObject(PopupListboxItemEhSortAsc);
if Index >= 0 then
Items.Delete(Index);
Index := Items.IndexOfObject(PopupListboxItemEhSortDes);
if Index >= 0 then
Items.Delete(Index);
Processed := True;
end;

Now library can fill list of unical values only for DataSet of TMemTableEh type. To fill values
when grid is connected to other type of DataSet, it is required rewrite
TDatasetFeaturesEh.FillSTFilterListDataValues method and , if it is need, it is required to
register class that inherited from TDatasetFeaturesEh. Read information about
TDatasetFeaturesEh class in EhLib users guide and EhLibMTE.Pas.

New properties STFilterDefaultStringOperator, STFilterDefaultNumberOperator,


STFilterDefaultDateTimeOperator, STFilterDefaultBooleanOperator are added in
TDBGridEhCenter class. Use this properties to set default operator that will be used when
string in the STFilter doesn't containt operator. The operators can be assigend appart for String
fields, Numeric fields, DataTime fields and logical fields.

Customizing grid title.

Complex titles.

TDBGridEh allows to create one common title above several columns. See Figure:
To do it, set DBGridEh.UseMultiTitle property to True value and fill label of the fields or caption
of column title using next rule: every part of text in field label or column title must consist of
several parts divided by sign "|", where every common part must be same for several required
columns. Other fields or captions must contain same text in the corresponding parts.
For example:
Field1.DisplayLabel := 'Title1|SubTitle1';
Field2.DisplayLabel := 'Title1|SubTitle2';
or
DBGridEh.Columns[0].Title.Caption := 'Title1|SubTitle1';
DBGridEh.Columns[1].Title.Caption := 'Title1|SubTitle2';

Title acts as a button.

Set Column.Title.TitleButton to True to make title cells act as a button. You can also write an
OnTitleBtnClick event to take specific action when the user clicks on title cell.

Show bitmaps in titles.

Use TitleImages property of TDBGridEh and ImageIndex property of TcolumnTitleEh to show


bitmap in titles instead of caption.

Default values for title properties.

Use TDBGridEh.ColumnDefValues.Title property to set default values for title properties.

Customizing Indicator column.


The Indicator Column is usually shown at the very left part of the Grid and is colored in
red color (The color varieties depending of current color scheme in the Windows). The
Indicator Column can display such information as: Indicator of the current record (Is
shown as triangular), State of editing, the number of the current record and checkbox of
selected record. Use properties of TDBGridEh.IndicatorOptions property to
customize the Indicator Column.

TDBGridEhIndicatorOptions = set of TDBGridEhIndicatorOption;


TDBGridEhIndicatorOption = (gioShowRowIndicatorEh, gioShowRecNoEh,
gioShowRowselCheckboxesEh);
gioShowRowIndicatorEh –Display indicator of current record in the indicator column.
gioShowRecNoEh – Display the number of the current record in the indicator column.
This property works only for DataSets that support IsSequenced mode (See Help about
TDataSet.IsSequenced).
gioShowRowselCheckboxesEh – Display checkbox of selected record. At runtime, user
can select records by clicking on checkboxes. Bookmarks of selected records are stored in the
TDBGridEh.SelectedRows or TDBGridEh.Selection.Rows collection.

Customizing grid footer.

Footers and total values.

TDBGridEh can display special row (footer) or rows at bottom part. Use FooterRowCount
property to specify the number of footer rows in the grid. Use Footer or Footers property of
TColumnEh object to specify information which needs to show in footer cells. Footers property
is useful when you have more than one footer rows. Footers are a collection of
TColumnFooterEh objects. Information from i-th element of collection will be shown in i-th row
of footer. In footer cell, it is possible to show: Sum value for the specific field, records count, the
value of a specific field or static text. Use property Footer.ValueType or Footers[i].ValueType to
specify which type of value will be shown in the footer cell. If ValueType = fvtStaticText, then
you also need to set Value property to specify text which will be shown. If ValueType =
fvtFieldValue, then you need to set property FieldName to specify the field, value of which will
be shown. To force grid to calculate total values you need to activate SumList (Set
DBGridEh.SumList.Active to True value).
Set TColumnFooterEh.ValueType to fvtSum to show sum value of the column field in the footer
cell, you can also specify Column.Footer.FieldName to calculate total value of the other field.
Set ValueType to fvtCount to force grid to display count of records in the footer cell.

Customizing grid cells.

Showing bitmaps in data cells depending on the field values.

TDBGridEh allows to show bitmaps from TImageList component depending on the field values.
In order to show bitmaps you need:
1. Fill list Column.KeyList property by the possible field values (every value in the separated
line) and set Column.ImageList property by the TImageList control that has the bitmaps. Every
image in ImageList corresponds to the string line in the KeyList property. You can also set
Column.NotInKeyListIndex property to the index of bitmap that will be shown if the field's
value does not correspond to any value in the KeyList (for instance you can set index of image
for Null field value). At run time you can’t edit cells with bitmaps. Use SPACE key or mouse
click to set value from next line of Column.KeyList to the field. Use Shift+SPACE key or
Shift+Mouse click to set value from previous line Column.KeyList. You can also set
Column.DblClickNextval to True to allow changing values in cell by double mouse clicking.

Showing pictures from DataSet fields in the grid cells.

TDBGridEh can show graphic data in the grid cell from TBlobField fields that have ftGraphic
type. Set DrawGraphicData property in True to force the grid to show images from Graphic
fields.

Checkboxes for Boolean and non Boolean fields.


Grid automatically shows checkboxes for Boolean fields. To show checkboxes for no Boolean
fields, fill first line of Column.KeyList property by value (or values) that corresponds to the
checked state of the checkbox. Fill second line for non-checked state, and set
Column.Checkboxes property to True. One line of KeyList can contain more than one value. In
that case every value must be separated by semicolon.

Data row height.

Use RowHeight and RowLines properties to specify the height of data row. Full height of data
row is calculated as height in text lines of RowLines plus RowHeight. Set RowSizingAllowed to
True value so that user can change height of row using mouse at run time.

Set Column.WordWrap to True value to break a long text in data row to a multiline. In reality,
text will be wrapped only when height of row is bigger than height of one text line.

Individual height of each data row.

TDBGridEh can work in mode when the height of every row is calculated dynamically
depending on the text in the grid cells or size of image in the cell (When DrawGraphicData value
is True). Include dghAutoFitRowHeight in OptionsEh property to force grid to calculate height
for every row. This mode works only when the grid is connected to the DataSet of
TMemTableEh type and TMemTableEh is not in TreeView mode. When dghAutoFitRowHeight
is included, grid calculates the height of the row dynamically using cell text
(TColumnEh.WordWrap property also influence it) and for column the fields of which have
ftGraphic type. To avoid surplus recalculation, grid recalculates heights, but not for after every
change of properties. For instance, grid does not update heights if the Font property was
changed. In such cases it is necessary to call UpdateAllDataRowHeights method. For more
flexible calculation of the heights the grid has an OnGetRowHeight event, in which you can
specify the height of row. During the event calling, the MemTableEh positions on record and we
can calculate the height of this record, so you can use MemTableEh properties to access fields
values.

Draw memo fields.

To draw memo fields as text set DrawMemoText to True.

Customize cells font attributes and color.

TDBGridEh properties Font and Color describe the font and color which is used to draw cells in
the grid.
TColumnEh properties Font and Color describe the font and color which is used to draw cells in
the specified column.

Events to customize cell’s font attributes and color.

There are several events that allow you to customize cell’s font attributes and color before the
cell data will be drawn. In the time of calling these events the DataSet is positioned on the record
that need to draw, so in the events you can access field values using such methods as
TDataSet.FieldByName(..).Value. Do not change grid properties or columns properties in these
events. It can bring to recirculation of the program.

TDBGridEh.OnDrawColumnCell
Write OnDrawColumnCell event to overload the standard method of the drawing cell. This event
is called after standard drawing, so the information will be drawn above standard-drawn contents
of cell. You may print the additional data, using methods of TDBGridEh(Sender).Canvas
property.

TDBGridEh.OnDrawDataCell
Do not write an OnDrawDataCell event handler. OnDrawDataCell is obsolete and included for
backward compatibility.

TColumnEh.OnAdvDrawDataCell or
TDBGridEh.OnAdvDrawDataCell
Write this event to draw data in the grid cell. In code of the event we set Processed parameter in
True value to define that the process of drawing was performed in event. Otherwise grid will call
method for default drawing of cell data. You may, if necessary, change such parameters as ARect
or Params. After changing the parameters call Grid.DefaultDrawColumnDataCell method and set
Processed to True value. You can also leave Processed parameter in False state and don’t call
Grid.DefaultDrawColumnDataCell. In that case, grid will call default drawing procedure using
changed parameters. Use Grid.Canvas property to draw data in the cell by yourself.

TDBGridEh.OnGetCellParams or
TColumnEh.OnGetCellParams
Write OnGetCellParams event to set such parameters as Font, cell color or other parameters
of cell before cell will be drawn. If it is needed to change parameters only in a specified column
then use column event - TColumnEh.OnGetCellParams. In this event you may change Font,
Color, Alignment, ImageIndex, Text, checkbox's state and also such properties of a Params
parameter as:
BlankCell: Boolean. Set this property to true to show cell as an empty cell with
3D border.
SuppressActiveCellColor: Boolean. Set this property to forbid the color of
active cell to overlay the color that is set in Background property.
TextEditing: Boolean. Set this property to forbid showing of cell text editor.
These events are also called when grid request Font and Color for inplace editor.
If you want to draw data by yourself use OnAdvDrawDataCell event.

Drawing of a ProgressBar shaped image in the Grid’s cell.

Grid doesn’t allow customizing column to show ProgressBar shaped image, but
there is a procedure DrawProgressBarEh in the ToolCtrlsEh module. You can
use it to draw image of ProgressBar when an event of custom drawing of a
Grid’s cell is used.
Below you can see an example of using of the DrawProgressBarEh procedure:

procedure TForm1.DBGridEh6Columns3AdvDrawDataCell(Sender: TCustomDBGridEh;


Cell, AreaCell: TGridCoord; Column: TColumnEh; const ARect: TRect;
var Params: TColCellParamsEh; var Processed: Boolean);
begin
Sender.DefaultDrawColumnDataCell(Cell, AreaCell, Column, ARect, Params);

DrawProgressBarEh(mtTable1.FieldByName('ItemsTotal').AsFloat, 0, 50000,
Sender.Canvas, ARect, clSkyBlue, cl3DDkShadow, clNone);
Processed := True;

end;
Default values for column properties.

To set default values for column properties use ColumnDefValues property. New created
columns will take property values from ColumnDefValues properties and will hold them till first
assign new value.

Hints and Tooltips


Hints and Tooltips are special text hints, which are shown in small additional window (usually in
a yellow color) while the mouse is above a specified place of grid. To show Hints and Tooltips in
DBGridEh it is required to set ShowHint property to True. Hints usually contain additional
information about a data in the cell. Tooltips usually contain a full-text of cell if it doesn’t fit in
the cell. To show Tooltips in DBGridEh, use the Column.ToolTips, Column.Title.ToolTips, and
Column.Footer.ToolTips properties. Besides, there are events Column.OnDataHintShow and
Column.DBGridEh that allow to form Hints for cell dynamically. Use these events to set Text,
Font, Colour, Position or the other parameters of hint window for every cell of the grid. These
events will be called only if Grid.ShowHint is set in True. During the calling event the grid is
positioned on required record. So you can access fields values from dataset.

Customizing in place editor in grid cell.

Banning of text editing in the cell.

Use property column TextEditing to ban text editing in the cell. It is allowed to ban text editing
dynamically in the OnGetCellParams event. In the event use Params.TextEditing parameter to
allow or ban text editing.

Several fields in the dropdown lookup list.

Fill olumn.LookupDisplayFields by the list of fields to show several fields in lookup list for
lookup fields. Semicolons should separate multiple field names. Name
Column.Field.LookupResultField must be present in LookupDisplayFields list. Lookup list with
several fields can be applied only for lookup fields.

Column with simple lookup values.

You can show another text in column depending on field values. Use KeyList and PickList
property. KeyList have to contain values which kept in the field and PickList have to contain a
values to show corresponding lines. Set Column.NotInKeyListIndex to the index of line from
PickList that will be shown if the field value is not contained in the KeyList (for instance you
can set index of line for Null field value). Set Column.DblClickNextval to True value to allow
user to change value in the cell by double click.

Dropdown calendar.

For TDateField and TDateTimeField fields Inplace Editor will show dropdown button to show
dropdown calendar. Set Column.ButtonStyle to cbsNone to prevent showing the dropdown
button.

Inplace Editor Color and Font.


Inplace Editor takes Color and Font from cell color. Cell takes Color and Font from Column
Color and Font, and OnGetCellParams event. Inplace Editor automatically set multiline mode
when row height bigger than the height of a text line and property WordWrap for column is True.

Automatically fits the width of the grid columns to the width of the
grid client area.
Set AutoFitColWidths to True value for automatic column resizing for fitting grid width equal to
width of grid’s visible part. MinAutoFitWidth property determines the minimum width of grid
when grid recalculates columns width.

3D and flat look.


Use OptionsEh property to show/hide 3D frame for fixed, frozen, footer and data rows.
Use Flat property to show grid in the flat style.

Drawing information about the absence of records in a dataset.


Grid allows to show special text in the central part of client area about absence of records in a
dataset. If the DataSet is active and haven’t any record then grid will draw text <No Records>.
Use subproperies of
TDBGridEh.EmptyDataInfo property to
customize Text and Font of this information.
By default the text about absence of records
is taken from global constant SNoData. You
can set Text for every Grid using
TDBGridEh.EmptyDataInfo.Text property
or set global variable DBGridEhEmptyDataInfoText from DBGridEh unit.

Using properties of TDBGridEh.IndicatorTitle.


Using properties of the TDBGridEh.IndicatorTitle object you can control the behavior of the grid
when the left-top cell is clicked.

Set TitleButton property to True value to make top-left cell working as button. When TitleButton
is True the properties DropdownMenu and UseGlobalMenu are also taken into consideration. If
UseGlobalMenu is True then grid will form the dropped down menu using global property
DBGridEhCenter.IndicatorTitleMenus.IndicatorTitleMenus. If DropdownMenu is also assigned
then all elements of this menu will be added to the dropped down menu after elements of global
menu.
Subproperies of IndicatorTitle property:
property DropdownMenu: TPopupMenu;
Identifies the pop-up menu, which elements will be displayed when IndicatorTitle cell is
clicked.

property ShowDropDownSign: Boolean default False;


Determines whether to display the black triangle in upper left when cell of the grid.

property TitleButton: Boolean;


Determines whether the upper left cell works as button.

property UseGlobalMenu: Boolean default True;


Determines whether grid will take into account the DBGridEhCenter.IndicatorTitleMenus
property to form drop down menu.

Using global properties for TDBGridEh.


The Library has a set of global properties and event, which influence all grids that are created in
the project. You can adjust this properties or event, for instance, in the main Form of your
project, and all grids of the project will change its behaviors according to these properties. To
control the global behavior of grids there are global objects such as the TDBGridEhCenter and
TDBGridEhStyle type. The First one is used to control the behavior of the grids, the second one
is to control the style of grids showing.

General information about TDBGridEhCenter class:


Use global function DBGridEhCenter to access the elements of the TDBGridEhCenter object:

function DBGridEhCenter: TDBGridEhCenter;

It returns the global object of the type TDBGridEhCenter, which controls the behavior of all
grids. You may inherit TDBGridEhCenter class, rewrite virtual methods and register your object
of managing using SetDBGridEhCenter function:

function SetDBGridEhCenter(NewGridCenter: TDBGridEhCenter):


TDBGridEhCenter;

It set new object of management and returns the old object. The Old object, in most cases, is
required to destroy.

Properties and events of the TDBGridEhCenter class:

Properties:
property FilterEditCloseUpApplyFilter: Boolean;
Determines whether the SubTitleFilter will be applied right after choosing value from
dropped down list or always need to press Enter key to apply filter.

property IndicatorTitleMenus: TDBGridEhStyleIndicatorTitleMenusEh;


Specifies the list of elements, which will be visible in IndicatorTitle of dropped down
menu when TDBGridEh.IndicatorTitle.UseGlobalMenu = True and
TDBGridEh.IndicatorTitle.TitleButton = True.

TDBGridEhStyleIndicatorTitleMenusEh is a set which consists of following values


itmVisibleColumnsEh- Display the menu item with list of columns, cliquing on
which possible to show or hide column.
itmCut - Display Cut menu item
itmCopy - Display Copy menu item
itmPaste - Display Paste menu item
itmDelete - Display Delete menu item
itmSelectAll - Display SelectAll menu item

Events:
OnApplyFilter: TNotifyEvent;
This event is called when grid apply SubTitleFilter. Sender parameter is a grid that
applies filter. In the handler of event you can call default handler -
DBGridEhCenter.DefaultApplyFilter.

OnApplySorting: TNotifyEvent;
This event is called when grid apply sorting. Sender parameter is a grid that applies
sorting. In the event handler you can call default handler -
DBGridEhCenter.DefaultApplySorting.

OnBuildIndicatorTitleMenu: TDBGridEhBuildIndicatorTitleMenu;
This event occurs when grid forms the dropped down menu that appears when mouse is
clicked on the upper left cell of grid. Event occurs if TDBGridEh.IndicatorTitle.TitleButton =
True. Sender parameter is a grid in which IndicatorTitle button was pressed. PopupMenu
parameter is a menu that will is displayed under cell. You can call default handler that build
menu items by default:
DBGridEhCenter.DefaultBuildIndicatorTitleMenu(Grid, PopupMenu);
and then perform additional code, for instance, to add one more menu elements.
// Below is an example that demonstrate how to add new menu item in list of IndicatorTitle menus.

// Declare global menu item for printing the grid.


var DBGridEhPreviewIndicatorMenuItem: TDBGridEhMenuItem;

// In public section of main Form declare methods for OnBuildIndicatorTitleMenu event.


procedure BuildIndicatorTitleMenu(Grid: TCustomDBGridEh; var PopupMenu: TPopupMenu);
// Event procedure that will be call when menu item is selected.
procedure MenuEditClick(Sender: TObject);

// In TMainForm.OnCreate event of the program, assign the event on that will be form IndicatorTitle menu items.
procedure TForm1.FormCreate(Sender: TObject);
begin
DBGridEhCenter.OnBuildIndicatorTitleMenu := BuildIndicatorTitleMenu;
end;

// Method Itself.
procedure TForm1.BuildIndicatorTitleMenu(Grid: TCustomDBGridEh; var PopupMenu: TPopupMenu);
begin
// At first it calls the default method of menu building.
DBGridEhCenter.DefaultBuildIndicatorTitleMenu(Grid, PopupMenu);

// Then create new item.


if DBGridEhPreviewIndicatorMenuItem = nil then
DBGridEhPreviewIndicatorMenuItem := TDBGridEhMenuItem.Create(Screen);
DBGridEhPreviewIndicatorMenuItem.Caption := 'Preview';
DBGridEhPreviewIndicatorMenuItem.OnClick := MenuEditClick;
DBGridEhPreviewIndicatorMenuItem.Enabled := True;
DBGridEhPreviewIndicatorMenuItem.Grid := Grid;

// And add it at the end of the menu list.


PopupMenu.Items.Insert(PopupMenu.Items.IndexOf(DBGridEhSelectAllIndicatorMenuItem)+1,
DBGridEhPreviewIndicatorMenuItem);

end;

// The Handler of new menu item.


procedure TForm1.MenuEditClick(Sender: TObject);
begin
PrintDBGridEh1.DBGridEh := TDBGridEh(TDBGridEhMenuItem(Sender).Grid);
PrintDBGridEh1.SetSubstitutes(['%[Today]',DateToStr(Now)]);
PrintDBGridEh1.Preview;
end;

OnCellMouseClick: TGridEhCellMouseEvent;
type TGridEhCellMouseEvent = procedure (Grid:
TCustomGridEh; Cell: TGridCoord;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of
object;
This event occurs on mouse clicking in any cell of the grid. Event has such parameters:
Grid; coordinates of the cell (Cell); Button, which was pressed on mouse (Button); Shift state of
keyboard (Shift) and coordinates of the clicked point inside cell (X, Y). In the handler of event
you can call the default handler - DBGridEhCenter.DefaultCellMouseClick.

OnIndicatorTitleMouseDown: TGridEhCellMouseEvent;
type TGridEhCellMouseEvent = procedure (Grid:
TCustomGridEh; Cell: TGridCoord;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of
object;
This event occurs when the mouse click on upper left cell of the grid occurs. In the
handler of event you can call default handler -
DBGridEhCenter.DefaultIndicatorTitleMouseDown.

OnLocateText: TLocateTextEventEh;
type TLocateTextEventEh = function (Sender: TObject;
const FieldName: string; const Text: String; Options:
TLocateTextOptionsEh; Direction: TLocateTextDirectionEh;
Matching: TLocateTextMatchingEh; TreeFindRange:
TLocateTextTreeFindRangeEh): Boolean of object;
This event occurs during increment or dialogue searching in the grid.

The General information about TDBGridEhStyle class:


To access elements the global DBGridEhStyle object use function:

function DBGridEhStyle: TDBGridEhStyle;

It returns the current object of the type TDBGridEhStyle, which controls imaging of all grids.
You can inherit TDBGridEhStyle, overwrite virtual methods controlling image of the grid, and
register new object to manage, using next function:

function SetDBGridEhStyle(NewGridStyle: TDBGridEhStyle):


TDBGridEhStyle;

Call this function to set new object of image controlling. It returns old object. In most cases it is
necessary to delete old object.

Properties of the TDBGridEhStyle class:

property LuminateSelection: Boolean default True;


This property determines whether need to illuminate the selected area in grid. If
LuminateSelection = False then the selected area will be painted by clHighlight color. If
LuminateSelection = True then selected area will be painted by method as if you see on the area
through the transparent glass of the clHighlight color.

property IsDrawFocusRect: Boolean default True;


This property determines whether to draw pointed square around the current cell or row
in the grid.
Import/Export TDBGridEh data to/from various formats.
EhLib have a set of functions to export data from DBGridEh to Text, Csv, HTML, RTF, XLS and
internal formats. It can write data to stream (TStream object) or to file.
Example
Pascal:
SaveDBGridEhToExportFile(TDBGridEhExportAsText,DBGridEh1,'c:\temp\file1.txt',False);
C++:
SaveDBGridEhToExportFile(__classid(TDBGridEhExportAsText),DBGridEh1,"c:\\temp\\file1.t
xt",false);

EhLib have set of functions to import data from Text and internal formats to DBGridEh's dataset.
It can read data from stream (TStream object) or from file.

Other features.

Frozen zone.

Frozen zone is columns the left part of the grid that remains unchanged when the grid is scrolled
to the left or right direction. Unlike the fixed columns the frozen columns can receive the edit
focus. To specify the count of the un-scrolling columns you need to set FrozenCols property.

Increment search

TDBGridEh allows users to accomplish a special "increment" search in grid columns. When user
enter in increment search mode, he can type chars and grid will try to locate text in the current
column. Use dghIncSearch and dghPreferIncSearch values (OptionsEh property) to customize
increment search in the grid. dghIncSearch value allows to perform incremental search in grid.
At run time you can use next keys for incremental searching:
Ctrl+F - to begin increment searching.
Ctrl+Enter - to search next matching.
Ctrl+Shift+Enter - to search prior matching.
If dghIncSearch in OptionsEh and column is read only then grid will enter in increment search
mode automatically after first key press and will return to normal mode after 1.5 sec.
dghPreferIncSearch value determines that the grid will set increment search mode automatically
after first key press instead of cell editing.

Multiselect

TDBGridEh allows to select records, columns and rectangle areas for following operations above
the selected area.
To customize multiselecting you can use next properties:
dgMultiSelect in Options property - Specifies whether the multiselect is allowed.
dghClearSelection in OptionsEh property - Specifies whether the selection will be cleared
after user move to the next cell.
EditActions property - Specifies actions which user can execute above the selection
(Copy,Cut,Delete,Paste,SelectAll).
AllowedSelections - Specifies the types of selections that is allowed to do (Rows, Columns,
Rectangle area, All).
Selection property specifies a current multiselection state, selected records, columns or
rectangle area and it has properties and functions to access them.
Save and restore grid and columns layout to/from registry or ini file.

TDBGridEh have set of routines to save and restore grid and columns layout to/from registry or
Ini file:
RestoreColumnsLayout - Restore Columns Order , Width , SortMarker from registry.
RestoreColumnsLayoutIni - Restore Columns Order , Width , SortMarker from the ini file.
RestoreGridLayout - Restore Columns Order, Width, Visibility, SortMarker, Sortmarked
index and/or row height from registry.
RestoreGridLayoutIni - Restore Columns Order, Width, Visibility, SortMarker, Sortmarked
index and/or row height from the Ini file.
SaveColumnsLayout - Save Columns Order, Width, SortMarker in registry.
SaveColumnsLayoutIni - Save Columns Order, Width, SortMarker in the ini file.
SaveGridLayout - Save Columns Order, Width, Visibility, SortMarker, Sortmarked index
and row height in registry.
SaveGridLayoutIni - Save Columns Order, Width, Visibility, SortMarker, Sortmarked index
and row height in the Ini file.

Converting existing TDBGrid component to TDBGridEh.


Although TDBGridEh is not inherited from TCustomDBGrid component, there are many alike
properties in TDBGridEh and in TDBGrid.
It allows us to convert existing TDBGrid component to TDBGridEh with minimum losses.
To convert existing TDBGrid component to TDBGridEh follow next instructions:
Open Form with TDBGrid component in Delphi IDE.
Open Form as Text (Alt-F12)
Rename all TDBGrid objects to TDBGridEh ('object DBGrid1: TDBGrid' -> 'object DBGrid1:
TDBGridEh')
Switch to view Form back as a Form (Alt-F12)
Rename all TDBGrid objects in Form declaration to TDBGridEh ('DBGrid1: TDBGrid;' ->
'DBGrid1: TDBGridEh;' )
Try to recompile project.
Using TPrintDBGridEh component
TPrintDBGridEh allows printing DBGridEh components on the printer.
Select TPrintDBGridEh in Delphi IDE component palette and drop it on a form. Select
TDBGridEh component in DBGridEh property. Use Print and Preview procedure to print grid on
a printer or to preview grid in a preview Form.

Rich text before and after grid


TPrintDBGridEh allows to print/preview rich text before and after grid. Use AfterGridText and
BeforeGridText to specify text. Using SetSubstitutes method you can substitute text in
BeforeGridText and AfterGridText properties upon print/preview process.

Features that current version of TPrintDBGridEh is not supported.


This version of TPrintDBGridEh does not support next features:
TPrintDBGridEh can not print/preview several grids on the single page.

FAQ List:

Q: How to print/preview grid on page in landscape orientation.

A: TPrintDBGridEh doesn’t have special properties to set page orientation. To do it, you need to
set orientation of virtual printer before calling Print or Preview procedure. Like this code:

uses ......, PrViewEh, Printers.


..............
procedure TForm1.bPreviewClick(Sender: TObject);
begin
PrinterPreview.Orientation := poLandscape;
PrintDBGridEh1.Preview;
end;
Using TDBSumList component

Common understanding of TDBSumList.


You can use TDBSumList for totaling records in a TDataSet with visible dynamic changes. Set
the DataSet field in the dataset for which you want to get and write SumListChanged event to
take specific action after TDBSumList has changed. TDBSumList has SumCollection property
that represents a container of TDBSum objects. Every TDBSum object represents an element
that can hold specific aggregation value. FieldName and GroupOperation determine type of
aggregation value, SumValue hold current aggregation value.

TDBSumList is embedded in DBGridEh component, so that all below text in equal degrees
pertains as to TDBSumList component and to TDBGridEh.SumList property.

How it works and why SumList sometimes calculate aggregation


values incorrectly.
Data-aware controls interact with dataset via TDataLink object. TDataLink does not allow to
recalculate aggregation value quickly. For instance when the record is deleted from dataset,
dataset sends deDataSetChange event to all TDataLink objects, same event is sent when the local
filter have been changed. So TDataLink can’t define why it gets this event and when it receives
such event then it has to recalculate aggregation values running through whole dataset, even
when if only one record was deleted from dataset. SumList doesn’t use these events and after
activation, it reassigns following events of the dataset: OnAfterEdit, OnAfterInsert,
OnAfterOpen, OnAfterPost, OnAfterScroll, OnBeforeDelete, OnAfterClose. This way allows us
to avoid of going through whole dataset when it is not needed. But other problems may appear,
such as:
Assigning these events at runtime. Deactivate SumList before assigning one of the earlier
described events at runtime.
Under some conditions SumList can raise exception of access violation. It can happen when
SumList tries to assign events back to dataset which had been already deleted. Such situation can
appear when SumList (or DBGridEh) and dataset are placed in different forms (or
DataModules). In such situation try to deactivate SumList before the Form or DataModule which
contains dataset is deleted.
SumList can not trace changes in dataset if you use SetRange or ApplyRange methods of
TBDEDataSet’s. Call SumList.RecalAll after using such methods.
SumList can’t trace changes in master dataset for detail dataset but not for BDE datasets. Call
SumList.RecalAll after changing active record in master dataset.
In any other case if you see that under some conditions SumList calculates values incorrectly call
RecalAll method.
If DBGridEh is connected to TMemTableEh then you can show aggregated values in grid using
Aggregated fields of TMemTableEh and no need to use TDBGridEh.SumList properties.
TMemTableEh uses internal methods to calculate Aggregated fields and doesn’t reassign events.
See description of TMemTableEh for detail information about Aggregated fields.
Using data-aware edit controls

Common understanding of edit controls.


EhLib has a set of data-aware edit controls to edit data: TDBEditEh, TDBDateTimeEditEh,
TDBComboBoxEh, TDBNumberEditEh and TDBLookupComboboxEh. EhLib doesn’t have not
data-aware version of these controls because every control can work as in data-aware mode and
not in data-aware mode. The base class for every edit control is TCustomDBEditEh.
TCustomDBEditEh encapsulates the behavior that is common for all edit controls for editing text
and if it is required for editing a DataSet’s field by introducing methods and properties that
provide:

Basic text editing functions such as selecting text, modifying selected text, and case
conversions.
Properties for making it read-only or introducing a password character to hide the actual value.
Validity checking using an edit mask.
Writing edited text to database field.
Showing one or several edit buttons (with variable glyphs: dropdown arrow, Ellipsis arrow,
up-down arrows, plus sign, minus sign or custom bitmap) at right part of edit box,
Showing image from image list at the left part of the edit box.

Application can use Text (String type) and Value (Variant type) properties to get and set string or
variant values to controls. Text property is a text that you can see in control. Value property hold
value of variant type and can hold values of types depending of control type. It can hold Null
value or:
String type value for TDBEditEh and TDBComboBoxEh,
TDateTime, TDate, TTime, Double type value for TDBDateTimeEditEh,
All numeric types value for TDBNumberEditEh,
TDBLookupComboboxEh control hold value that depends on type of the field.

If control is connected to the field then the assignment data to the Text or Value properties
automatically write data to the field.

Every control has Flat and AlwaysShowBorder properties to control the border appearance.

All controls have EmptyDataInfo property that allows customize


edit control to draw special text and font when control have no
data (Edit1.Text = ‘’).

Working with edit buttons.


Every edit control allows to have one or more edit buttons on the right side. You can use
EditButton and EditButtons to control them.

Using TDBDateTimeEditEh control.

TDBDateTimeEditEh represents a single-line date or/and time edit control that can display and
edit a date or/and time values.
Property Kind determines whether the component is a date editor or/and a time editor
(dtkDateEh, dtkTimeEh, dtkDateTimeEh) or custom date-time mask editor (dtkCustomEh).
Use EditFormat property to set custom date/time format. You can use next format elements:
'YY', 'YYYY', 'MM', 'DD', 'HH', 'NN', 'SS'.
By default TDBDateTimeEditEh build edit mask using ShortDateFormat variable. Edit mask can
be by six types: three for four-char year - 'MM/DD/YYYY', 'DD/MM/YYYY', 'YYYY/MM/DD'
and three for two-char year 'MM/DD/YY', 'DD/MM/YY', 'YY/MM/DD'.

Application can use Text (String type) and Value (Variant type) properties to get and set
DateTime type value in TDBDateTimeEditEh. If TDBDateTimeEditEh has dtkDateEh type then
it will change only date part of the field. If TDBDateTimeEditEh has dtkTimeEh type then it will
change only time part of the field.

Using TDBNumberEditEh control.


TDBNumberEditEh represents a single-line number edit control that can display and edit
numeric values.

TDBNumberEditEh builds display text using DisplayFormat property and shows display text
when control is not active.

Use properties of EditButton object to customize the edit button on the right side of edit control.
When EditButton in UpDown style, the control will work as a Spin edit. Use Increment property
to specify the value that is added or subtracted from Value when the user calibrates the control.

Using TDBComboBoxEh control.


TDBComboBoxEh component is an edit box with a scrollable drop-down list attached to it. User
can select an item from the list or type it directly into the edit box.

TDBComboBoxEh permits a single line and multiple line of text. Use WordWrap property to set
TDBComboBoxEh as multiple line editor.

Use Items property to access to the list of items (strings) in the list portion of the combo box.

Use KeyItems property to access to the list of items (strings) which will be stored in field when
Items property is also assigned. When Items and KeyItems properties are filled, then KeyList
property have to contain values which will be written in the field, but Items property, in
corresponding indexes, has to contain values to display.

Use Images property to specify images that will be drawn in the drop-down list and image that
will be drawn on the left side of ComboBox. Index of drawing image is taken from ItemIndex
property.

Using TDBLookupComboboxEh control.


TDBLookupComboBoxEh represents a combo box that identifies a set of field(s) values in one
dataset with a corresponding set of values from another dataset. To understand 'lookup' concepts
see Delphi help, Topic - Displaying and editing data in lookup list and combo boxes.

TDBLookupComboboxEh can be of two styles (Style property):


csDropDownEh - Application can assign and users can type text which does not contain in data
list.
csDropDownListEh - Application can assign and users can type text which is only present in data
list.
If KeyField, ListField, ListSource, DataField and DataSource properties are empty then you can
assign KeyValue and Text values which doesn't affect each other.

Drop down window takes values from dataset that determines by ListSource property.
Drop down list can:
Show titles (Captions is took from Field.FisplayLabel property),
Show special non-scrolled row in top part of list (SpecRow propery).
Have sizing grip (Sizable property),
Automaticaly set width of window as sum of DisplayWidth of the list fields (Set Width
propery = -1),
Automaticaly drops when user presses any key (AutoDrop property).
Have specified width (Width property).

Using SpecRow in columns of DBGridEh component and in


DBLookupComboBoxEh component.
The SpecRow property of TDropDownBoxEh or DropDownSpecRow property of TColumnEh
holds a TDropDownBoxEh object. TDropDownBoxEh defines attributes of the special row in
the dropped down box. TSpecRowEh represents a special row in the top part of dropdown box
for lookup fields in column of DBGridEh and in TDropDownBoxEh class of
TDBLookupComboboxEh component. This row will be active when lookup field or
LookupComboBox has value that is equal to SpecRow.Value property.
TSpecRowEh contains next properties:
CellsText: String Specifies the text(s) that will be shown in the drop-down window for
SpecRow. When dropdown box have more than one columns, use
semicolon to separate text for each column.
Color: TColor Background color of special row in dropdown box.
Font: TFont Font of special row text.
Value: Variant Value. Special row is shown as selected (highlighted) when this Value is
equal to value of control to which this special row belong to.
Visible: Boolean Specify, whether the spec row is active and visible in the DropDown
box.
ShortCut: TShortCut Specify the shortcut for assigning value of SpecRow.Value property to
Control value.
ShowIfNotInKeyList: Specify, whether the SpecRow text will be shown in Control if the value
Boolean of the control is not in list of key values.
Using TPropStorageEh and TPropStorageManagerEh
components
TPropStorageEh and TPropStorageManagerEh componetns realize technology to store
components properties to/from settings storage such as Ini files, Registry etc.

Current version of library has components to write/read in/from Ini files and Windows Registry.
Base component of this technology is the TPropStorageEh. Place this component in the form,
component properties of which you want to save in the storage. Double click on the component
during the design-time to open properties storage editor window. In the tree of properties you can
select required properties for storing. Properties list is a list of all published properties or
declared in DefineProperty function of components with the exclusion of TCollection class
properties. Besides the list of all elements of the collection, the tree of properties will contain
<ForAllItems> subproperty. When you select sub-property in the given branch, the component
will save corresponding sub-property for each element of the collection.

Component TPropStorageEh can write and read property values in the stream. To redirect flow in
the storage it is necessary to execute one of the following actions:

1. Place component that is inherited from TPropStorageManagerEh on the form.


In this version there are two such components. These are TIniPropStorageManEh and
TRegPropStorageManEh.
Customize properties of this component and assign component to
TPropStorageEh.StorageManager property.

2. Or you can only once write code to register global component - DefaultPropStorageManager.
All TPropStorageEh components, in which StorageManager property is not assigned, will use
DefaultPropStorageManager manager for redirecting flow of the property values to the storage.

Code to register global store manager can look like this:


----------- MainUnit.Pas--------
......

var
IniPropStorageMan: TIniPropStorageManEh;

initialization

IniPropStorageMan := TIniPropStorageManEh.Create(nil);
IniPropStorageMan.IniFileName := 'MyIniFile.Ini';
SetDefaultPropStorageManager(IniPropStorageMan);
end.
--------------------------------
Introduction in technology of interaction between MemTable
and DataDriver.
This technology is intended for unified way of loading tabular information from the server to the
client with afterward processing these data on the client: editing, sorting, filtrations and
unloading changed data back to the server. This technology doesn’t include drivers to access
server but it have a set of components and global events to redirect flow of data to/from server
using your favorite access engine.

The technology is represented by two main components:

TMemTableEh - is a dataset that hold data in memory. Its possible to consider it as an array of
records.
Besides, this dataset:
Supports a special interface, which allows DBGridEh component to view and scroll data
without moving active record.
Allows to fetch data from TDataDriverEh object (DataDriver property).
Allows to unload changes back to DataDriver, instantly or postponed (in dependencies of the
CachedUpdates property).
Allows to create a master/detail relations on the client (filtering record) or on the external
source (updating parameters [Params] and requiring data from DataDriver).
Allows to sort data, including Calculated and Lookup field.
Allows to work in standalone mode. Allows to create structure and fill data at design-time
and save data in DFM file of the Form (When DataDriver property is not assigned).
Allows to keep record in the manner of trees. Each record can have records-branches and it
itself can be an element to other parental record. TDBGridEh component supports to show the
tree-type structure of these records.
Allows to connect to the internal array of other TMemTableEh (via ExternalMemData
property) and work with its data: sort, filter, edit.
Has interface for requesting list of all unique values in one column of records array, ignoring
local filter. TDBGridEh uses this property for automatic filling a list in DropDownBox of the
subtitle filter cell.

TDataDriverEh - carry out two tasks:


1. Delivers data to TMemTableEh.
2. Processes changed records of TMemTableEh (writes them in other dataset, or call
events for processing the changes in program for passing updates to the server).

Furthermore, there are several components that are inherited from TDataDriverEh. These are a
TSQLDataDriverEh, that have properties to keep five SQL expressions and parameters to: query
data, delete record, insert record, update record and require one record. TSQLDataDriverEh can’t
interact with server by itself, but can prepare parameters for request and can call global event to
transfer SQL expression for processing in application. There are several components which are
inherited from TSQLDataDriverEh and which can send SQL expressions to the server through
the corresponding access engine. These are TBDEDataDriverEh, TIBXDataDriverEh,
TDBXDataDriverEh and TADODataDriverEh components.
TMemTableEh component.
Two working mode of TMemTableEh component.
There are two working mode of TMemTableEh: ‘stand-alone’ and ‘with datadriver’.

‘stand-alone’ mode.
In ‘stand-alone’ mode TMemTableEh works as independent array of data. Before
working with such MemTable it is necessary to create an internal structure of record. For that it
is necessary to create external fields (TFields) or field definitions in TMemTableEh and call
CreateDataSet method (Or, at design-time, press ‘Create DataSet’ button in Fields editor
window).
'with datadriver' mode.
The 'with datadriver' mode is activated when TMemTableEh.DataDriver property is assigned.
Internal array is created automatically on activation of MemTableEh. On open the structure of
fields of internal array of records in MemTableEh depends on existents of persistent fields in the
MemTableEh.

ViewScroll
TMemTableEh supports special interface, allowing DBGridEh component to view all data
without moving active record. We will call such state as ViewScroll.

Master/detail relations.
Master/detail relation is a working mode of two datasets when all visible records of one dataset
(DetailDataSet) always correspond to one record of other dataset (MasterDataSet). In time of
moving in MasterDataSet the DetailDataSet will recreate or filters records so that they will
correspond to MasterDataSet record. The correspondence is adjusted using MasterFields and
KeyFields properties of DetailDataSet. DetailDataSet always show only the records, which
values of the field/fields defined by MasterFields property is equal to values of the fields defined
by MasterFields property of the current record of MasterDataSet.
TMemTableEh allows to create a master/detail relations on the client side "mdsOnSelfEh" (by
filtering record) or on DataProvider "mdsOnProviderEh" (by recreating list of records in
DetailDataSet when record in MasterDataset is changed).
To adjust TMemTableEh in the master/detail mode use next properties: MasterSource,
MasterFields, KeyFields, MasterDetailSide. When MasterDetailSide is mdsOnSelfEh,
TMemTableEh will filter records by DetailFields fields using values of
MasterDataSet[MasterFields] fields. When MasterDetailSide is mdsOnProviderEh,
DetailDataSet will reopen itself, assigning parameters from MasterDataSet[MasterFields]. On
opening it will pass parameters to DataDriver. In the mdsOnProviderEh mode the DetailFields
are not used.

The third state of working "mdsOnSelfAfterProviderEh" is a combination of two preceding.


Upon first moving to record in MasterDataSet the DetailDataSet gets records from DataDriver,
sending him parameters with values, assigned from MasterSource[MasterFields] and add
received records in its internal array of record. Upon next moving on same record in
MasterDataSet the DetailDataSet will always only filter records locally.

Storing records in tree mode (TreeView).


In tree mode the TMemTableEh create node objects (TMemRecViewEh type) for each record in
the internal array. Node object have reference to parent record (Rec property) and has a list of
child nodes (NodeItems).
Adjusting TreeView mode is realized by subproperties of TMemTableEh.TreeList property.
TMemTableEh automatically adds new record in the tree, using field values defined by
TreeList.KeyFieldName and TreeList.RefParentFieldName properties. When new record is
appearances in MemTable, it tries to find Parent record in the list of existing records, it looks
throw records trying to find values of the field in KeyFieldName that is equal to the value of the
field defined by RefParentFieldName property in the new record. Furthermore, it checks, if this
record is a parent for other existing records in array. Building of tree can be speeding up, if you
create indexes for fields specified in TreeList.KeyFieldName and TreeList.RefParentFieldName
properties. However the maximum speed of building tree is possible to achieve if the records all
records will be appended in DataSet in valid sequence. In other words every record must be
added in DataSet in same order as it appears in the tree. In last case it is not recommended to
create indexes, it can only slow down building of tree. If records appear in DataSet in valid order
set FullBuildCheck to False. It will not check if the new record have child records in DataSet.

Subproperties of TMemTableEh.TreeList property:


Active: Boolean - Defines that TreeView mode is active. In TreeView mode you can access
TMemTableEh properties: TreeNodeLevel, TreeNodeExpanded, TreeNodeHasChildren,
TreeNodeChildCount for current record.
KeyFieldName: String - Holds a name of the key field of record. Child record will refer to
parental record with the key determined by the KeyFieldName field.
RefParentFieldName: String - Holds a name of the field that contain reference value to a
parent record.
DefaultNodeExpanded: Boolean - Defines a value of Expanded property for new elements
of the tree.
DefaultNodeHasChildren: Boolean - Defines a value of HasChildren property for a new
elements of the tree.
FullBuildCheck: Boolean – Defines if need check if there are Child records in array for new
record. Setting this property to False can speed up building of tree, but all child records must be
added after parent record.

Use next TMemTableEh properties to access state of the tree node for the current record of
DataSet:
RecView: TMemRecViewEh - a reference to the tree node of the tree, it is available only in
tree mode.
TreeNodeLevel: Integer - Indicates the level of the node in the tree.
TreeNodeExpanded: Boolean - Specifies whether the tree node is expanded.
TreeNodeHasChildren: Boolean - Indicates whether a node has any children.
TreeNodeChildCount: Integer - An amount of Child elements.

Working with AutoIncrement fields


TMemTableEh has an AutoIncrement property with InitValue and Step subproperties to work
with fields which values are generated by automatic sequence numbers. For such fields property
TField.AutoGenerateValue mast be arAutoInc. Values for such fields are generated automatically
using internal counter when the new record is appeared in the internal array. Initial value of the
counter is assigned by the TMemTableEh.InitValue property. After inserting new record, a value
of the counter increases on the number given by the TMemTableEh.Step property.
If TMemTableEh is connected to DataDriver then usually values of such fields are generated by
the server. To cause TMemTableEh be able to get values of fields generated by the server, it is
recommended to use TMemTableEh and TSQLDataDriver (or inherited from it) as follow:
Set InitValue property and Step property to -1. Values of AutoIncrement fields will have negative
values before sending the new record to the server.
Add parameters in TSQLDataDriver.SpecParams property to make SQLDataDriver be able to
get values of AutoIncrement fields generated by the server. List of parameters in
TSQLDataDriver.SpecParams depends on the type of Server and will be described later. After
updates are applied and record new writes to the server, SQLDataDriver will request new value
of the counter from server and assign it to the AutoIncrement field on the client.

Using indexes.
Indexes are used for speeding up searching. In particular it is used to building a tree-type
structure of records. Pattern of indexes is assigned in IndexDefs collection. TMemTableEh
creates indexes basing on the pattern when it making an internal array of records. It usually
happens when DataSet is activated).

Using shared array of records by several TMemTableEh’s.


TMemTableEh allows to use a same array of records by several TMemTableEh components.
But only one main TMemTableEh must be holder of the array. Others will connect to this array
using ExternalMemData property use it. Other TMemTableEh components access external data
of the main TMemTableEh ignoring local filter of main TMemTableEh. DataDriver property can
be assigned only for main MemTable. Sorting and filtration in each MemTableEh components
don’t affect to each other.

Moving records in TMemTableEh when dghRecordMoving mode is


active.
Include dghRecordMoving in OptionsEh of DBGridEh component to allow users moving
records inside TMemTableEh component. Besides, when TreeList mode is active, DBGridEh
allows move records inside tree by changing records and level of node. To move record at run-
time, a user has to press the mouse button above the indicator of record and drag it to required
place inside the grid (when multiselect is active user has to select records to move before
dragging).

TRefObjectField field type.


MemTableEh unit have code to register new type of field - TRefObjectField. TRefObjectField is
intended to keep the pointer to TObject type object and have Value property of TObject type. At
design-time choose ‘RefObjectField’ type in form of creating new field to create
TRefObjectField field. At run-time in the program you can create a field of this type by assign
ftUnknown value to DataType property of FieldDef object.

Using maintained aggregates


MemTableEh provide support for summarizing data over all records of DataSet.
MemTableEh keep aggregated values (such as SUM, COUNT) in TAggregateField field type. At
Design-time mode use Fields Editor to create persistent aggregated field. You can bind such
fields to TDBEditEh component or to the footer of TDBGridEh.

Records sorting.
TMemTableEh has two methods of the sorting: Sorting with dynamic supporting of the changes,
when the added record is automatically move to the necessary position to support order of the
sorting.
And sorting without dynamic supporting of the changes.
1. Use the SortOrder property to sort data with dynamic support of the changes. Separate
several fields by comma. Add ‘DESC’ after fieldname to sort data in inverse sequence. Sorting
occurs at the TRecordsViewEh object, so physically the records doesn’t move inside internal
array TRecordsListEh.
2. Use SortByFields procedure to sort data without dynamic support of the changes. The
string that define sorting must have same format as for SortOrder property. Sorting occurs on the
level of TRecordsListEh, i.e. records are sorted physically in the internal array of data.

When you use EhlibMTE unit for automatic sorting in DBGridEh you can use global variable
SortInView of Boolean type to define the type of sorting that will be executed when DBGridEh
performs sorting after sorting markers in titles of grid are changed.

Creation/removing table data in memory in the ‘stand-alone’ mode.


MemTableEh allows to create an internal array of records at design-time and at run-time. Before
creating the table data, you need to set properties to specify the structure of the table you want to
create. In particular, you need to specify structure of the fields of the new array.
There are two ways to do this:
First way, you can add field definitions to the FieldDefs property. At design time, double-click
the FieldDefs property in the Object Inspector to bring up the collection editor. Use the
collection editor to add, remove, or change properties of field definitions. At runtime, clear any
existing field definitions and then use AddFieldDef method to add each new field definition. For
each new field definition, set the properties of the TFieldDef object to specify the desired
attributes of the field.
Second way, you can use persistent field components instead. At design time, double-click on the
dataset to bring up the Fields editor. In the Fields editor, right-click and choose ‘New Field’
command. Describe the basic properties of your field. Once the field is created, you can alter its
properties in the Object Inspector by selecting the field in the Fields editor.
After creating field definitions or persistent fields, you need to create internal array. At Design-
time mode, click right mouse above dataset and choose 'Create DataSet'. This command does not
come up in the context menu until you define the whole necessary information.
To create an internal array at Run-time, you need to call CreateDataSet method.
If DataDriver property is assigned then internal array will be created automatically on activations
MemTable. At this case the structure of array MemTable get from DataDriver.

In ‘stand-alone’ mode when MemTable is closing it does not delete internal array of records. To
close MemTable with simultaneous deleting of all records and structure, use DestroyTable
method.
Use EmptyTable method to delete all records from MemTable.

Working with MemTableEh in the 'with datadriver' mode.


If TMemTableEh.DataDriver property is assigned then MemTable works in 'with datadriver'
mode. In this case internal array will be created automatically when MemTableEh become
active. On open the structure of fields of internal array of records in MemTableEh depends on
existents of Persistent fields in the MemTableEh. If persistent fields are exist at desing-time then
the structure of fields of internal array will be taken from the list of Persistent fields; otherwise
the structure will be taken from the DataDriver component.
If FetchAllOnOpen property is True then MemTableEh loads all records from DataDriver on
open. If FetchAllOnOpen is False then MemTableEh will not load records until application call
Next or FetchRecords methods. Method ‘Next’ checks that cursor is positioned at end of
MemTableEh, if not then it fetch next record and move to the next record in provider. Method
FetchRecords fetch more records from DataDriver and add it at the end of internal array of
MemTable. This method takes one parameter - an amount of records which need to fetch. To
fetch all record it is needed to pass ‘-1’ as parameter. When MemTable connected to DBGridEh
the Grid calls FetchRecords by itself via IMemTableEh interface to display all visible records in
the view area. If CachedUpdates property is False then changes are transferred right after Post
method. If CachedUpdates is True then data are not transferred until the ApplyUpdates method is
called.

Cached updates.
TMemTableEh can work in operative or postpone updates. CachedUpdates property defines type
if updates. In operative mode of the updates, TMemTableEh sends changed record to c right after
application call TMemTableEh.Post method or append new record in TMemTableEh. In the
postpone mode the updates aren’t sent to postpone, but are accumulated in the special buffer.
Data are not transferred until the client application calls the ApplyUpdates method. To turn on
the postpone updates you need set CachedUpdates property to True.
ApplyUpdates have a single parameter – MaxErrors. MaxErrors indicates the maximum number
of errors that the DataDriver should allow before prematurely stopping update operations. Set
MaxErrors to –1 to indicate that there is no limit to the number of errors. Set MaxErrors to 0 to
define that whole process of change will be rejected on first error. Records, which renovations
have come with errors, have an additional UpdateError property with type of TUpdateErrorEh.
To identify type of changing of record you need to use UpdateStatus method and StatusFilter
property:
UpdateStatus indicates a type of changing of current record in MemTable. It returns one of the
following values:
usUnmodified - Indicates that the current record haven’t been changed.
usModified - Indicates that the record was edited and changed.
usInserted - Indicates that the record was added.
usDeleted - Indicates that the record was removed.

StatusFilter defines filter for different types of records. StatusFilter – is a set that can contains
any combination of the following values:
usUnmodified – Unmodified records are visible in MemTable.
usModified - Modified records are visible in MemTable.
usInserted - Added records are visible in MemTable.
usDeleted – Deleted record are visible in MemTable.

By default, StatusFilter have [usModified, usInserted, usUnmodified] value. So, deleted records
are hidden.
Method RevertRecord restores an old condition of the current record and values of fields. If
record was added in the program, it is deleted from the list. If record was changed then
UpdateStatus property is restored to usUnmodified value.
Method MergeChangeLog deletes a log of cached changes. All added or changed records get
usUnmodified status.
Method CancelUpdates cancels all changes and restores old state of records array.

Marking and Returning to Records.


In addition to moving from record to record in a dataset (or moving from one record to another
by a specific number of records), you can mark a particular location in a dataset so that you can
return to this location. TDataSet introduces a bookmarking feature that consists of a Bookmark
property and five bookmark methods. In TMemTable, bookmarks contain the record number
(RecNo property).

The Bookmark property.

Bookmark gets or sets the current bookmark in a dataset. A bookmark marks a location in a
dataset so that an application can easily return to that location quickly.
An application can read Bookmark to retrieve the bookmark associated with the current record,
and it can change the current record in the dataset by assigning a saved bookmark value to this
property.

GetBookmark method

I do not recommend to use this method, use Bookmark property instead of it. See VCL
documentation for detail.

GotoBookmark and BookmarkValid method

When passed a bookmark, GotoBookmark moves the cursor for the dataset to the location
specified in the bookmark. Before calling GotoBookmark, you can call BookmarkValid to
determine if the bookmark points to a record. BookmarkValid returns True if a specified
bookmark points to a record.

CompareBookmarks method

You can also call CompareBookmarks to see if a bookmark you want to move to is different
from another (or the current) bookmark. If the two bookmarks refer to the same record (or if both
are nil), CompareBookmarks returns 0.

FreeBookmark method

This method is Used in combinations with GetBookamrk. I do not recommend to use this
method. See VCL documentation for detail.

Searching in TMemTableEh
You can search in TMemTableEh using following methods:

1. Locate

Locate moves the cursor to the first row matching a specified set of search criteria. In its simplest
form, you pass Locate the name of a column to search, a field value to match, and an options flag
specifying whether the search is case-insensitive or if it can use partial-key matching. (Partial-
key matching is when the criterion string need only be a prefix of the field value.) For example,
the following code moves the cursor to the first row in the CustTable where the value in the
Company column is "Professional Divers, Ltd.":

var
LocateSuccess: Boolean;
SearchOptions: TLocateOptions;
begin
SearchOptions := [loPartialKey];
LocateSuccess := CustTable.Locate('Company', 'Professional Divers, Ltd.', SearchOptions);
end;

If Locate finds a match, the first record containing the match becomes the current record. Locate
returns True if it finds a matching record, False if it does not. If a search fails, the current record
does not change.
The real power of Locate comes into play when you want to search on multiple columns and
specify multiple values to search for. Search values are Variants, which means you can specify
different data types in your search criteria. To specify multiple columns in a search string,
separate individual items in the string with semicolons.

Because search values are Variants, if you pass multiple values, you must either pass a Variant
array as an argument (for example, the return values from the Lookup method), or you must
construct the Variant array in code using the VarArrayOf function. The following code illustrates
a search on multiple columns using multiple search values and partial-key matching:

with CustTable do
Locate('Company;Contact;Phone', VarArrayOf(['Sight Diver','P']), loPartialKey);

Locate uses the fastest possible method to locate matching records. If the columns to search are
indexed and the index is compatible with the search options you specify, Locate uses the index.

2. Lookup

Lookup searches for the first row that matches specified search criteria. If it finds a matching
row, it forces the recalculation of any calculated fields and lookup fields associated with the
dataset, then returns one or more fields from the matching row. Lookup does not move the cursor
to the matching row. It only returns values from it.

In its simplest form, you pass Lookup the name of field to search, the field value to match, and
the field or fields to return. For example, the following code looks for the first record in the
CustTable where the value of the Company field is "Professional Divers, Ltd.", and returns the
company name, a contact person, and a phone number for the company:

var
LookupResults: Variant;
begin
LookupResults := CustTable.Lookup('Company', 'Professional Divers, Ltd.',
'Company;Contact; Phone');
end;

Lookup returns values for the specified fields from the first matching record it finds. Values are
returned as Variants. If more than one return value is requested, Lookup returns a Variant array. If
there are no matching records, Lookup returns a Null Variant.

The real power of Lookup comes into play when you want to search on multiple columns and
specify multiple values to search for. To specify strings containing multiple columns or result
fields, separate individual fields in the string items with semicolons.

Because search values are Variants, if you pass multiple values, you must either pass a Variant
array as an argument (for example, the return values from the Lookup method), or you must
construct the Variant array in code using the VarArrayOf function. The following code illustrates
a lookup search on multiple columns:

var
LookupResults: Variant;
begin
with CustTable do
LookupResults := Lookup('Company; City', VarArrayOf(['Sight Diver', 'Christiansted']),
'Company; Addr1; Addr2; State; Zip');
end;

Like Locate, Lookup uses the fastest possible method to locate matching records. If the columns
to search are indexed, Lookup uses the index.

3. FindRec

FindRec searches for the first row that matches specified search criteria and return record
number. FindRec have the same parameters as the Locate method.

When MemTableEh is in tree-view mode the Locate and FindRec methods search records in
expanded nodes. To search matches in all nodes you need to use MemTableEh.TreeList.Locate
method. This method also expand founded node, so it will be visible in dataset.

4. GotoRec
GotoRec moves the cursor to the row passed by the Rec parameter. GotoRec returns True if it
finds a record, False if it does not.

Quick access to the record values.


To get values of the fields from specified record in standard DataSet, it is necessary to move to
the required record. This not always suitable since when you move to the record using MoveBy,
RecNo, Bookmark methods calls events about changing the record position that can bring about
big delays and repaint of the screen.
There are several ways in MemTableEh that allow to get values of the fields without activations
record position.
1. You can use DisableControls, EnableControls methods to deactivate events about
changes in DataSet. Disadvantage of this way is that EnableControls causes event about
changes DataSet, that will repaint visual component connected to DataSet.
2. You can use InstantReadEnter, InstantReadLeave methods to enter in InstantRead mode.
InstantReadEnter enters in mode of viewing records and moves virtual position to the
record determined by the RowNum parameter. After that you can read but don’t change
values of record. Each call of InstantReadEnter method, must correspond call
InstantReadLeave. InstantReadLeave leave a viewing records mode. In InstantRead mode
it is not allowed to change values of record. InstantReadEnter and InstantReadLeave
methods do not send events about changing position in DataSet.
3. You can use properties to access internal array of records of MemTableEh. Internal
objects allow to access values of record as to the array of data with index. Besides you
may addresses to all writing an internal array given disregarding local filter. For access to
internal structures of data you need to use following properties of TMemTableEh:
RecordsView: TRecordsViewEh – filtered list of records.
RecordsView.Rec[Index: Integer]: TMemoryRecordEh – access to certain record in
filtered list of records.
RecordsView.Count: Integer – Count of records in the filtered list of records. In
TreeView mode list have only visible in expanded nodes.
RecordsView.MemTableData.RecordsList[Index: Integer]: TMemoryRecordEh –
access to certain record in the list of all records.
RecordsView.MemTableData.RecordsList.Count – Count of records in list of all
records.
RecordsView.MemTableData.RecordsList[Index: Integer].DataValues[const
FieldNames: string; DataValueVersion: TDataValueVersionEh]: Variant – access
to certain value of field in record specified by Index.

Copying data from/to another DataSet.


TMemTableEh affords the following methods for copying data from/to another DataSat:

SaveToDataSet method
Copying it own data in another DataSet, specified by Dest parameter. If RecordCount parameter
> 0, the copying begins from current record of source DataSet and copy not more then
RecordCount record. If RecordCount = 0 then all records will be copied. When copying the
MemTable always add records in Dest DataSet.

LoadFromDataSet method
Loads not more then RecordCount records from Source DataSet to itself. If RecordCount = -1
then it load all record. If Mode parameter is lmCopy then all data will be deleted before loading.
If Mode parameter is lmAppend then new records will be added to existing data.
UseIfCachedUpdates parameter define that new records gets usInserted status.

Internal objects of TMemTableEh component.

In most cases to work with data in TMemTableEh it is sufficient to use properties and
methods of the TMemTableEh. However in some cases it is necessary to work with data at low
level. TMemTableEh component keep records in internal array of records and has seven main
objects for processing the internal data:
TMemTableDataEh – Internal table of data. Is have two objects: TMTDataStructEh -
describes the structure of a table fields and TRecordsListEh containes a list of records of
TMemoryRecordEh type.
TMTDataStructEh – Describes structure of a table fields. Is have a list of objects that
inherited from TMTDataFieldEh class.
TMTDataFieldEh – base class that describe field type in internal table array. It is a parent for
such types as TMTStringDataFieldEh, TMTNumericDataFieldEh, TMTDateTimeDataFieldEh,
TMTBlobDataFieldEh, TMTBooleanDataFieldEh, TMTInterfaceDataFieldEh,
TMTVariantDataFieldEh, TMTRefObjectFieldEh.
TRecordsListEh – list of records.
TMemoryRecordEh – one record in list of record.
TRecordsViewEh – hold filtered list of records. Only those records that meet a
TMemTableEh.Filter conditions are hold in RecordsView.
Hold only records that TMemTableEh.Filter.
TMemoryTreeListEh – hold a tree-type list of TMemRecViewEh objects with references to
record.

Workig with TMemTableEh at design-time.


At design-time the double click on the component opens a window of component
controling - TMemTableFieldsEditor. It allows:
Create fields (TField components) for TMemTableEh.
Fill TMemTableEh datas.
Load data in TMemTableEh from other DataSet.
Create 'stand-alone’ array of datas.
Clean TMemTableEh.
Create new TDataDriver object for TMemTableEh basing on existing DataSet-source of
data. Herewith, designer will try to assign DataDriver properties founding on the type DataSet-
source. For instance, if you choose to create DataDriver of TSQLDataDriver type and DataSet-
source will have a TQuery type, the designer will assign
TSQLDataDriver.SelectComand.CommandText property automatically from TQuery.SQL
property.

TDataDriverEh component.
TDataDriverEh is universal data provider for TMemTableEh and a handler of the changes
in TMemTableEh. TDataDriverEh is a simplest supplier of datas, it is a agent between
TMemTableEh and other DataSet, that can to work with the database. Although many DataSet’s
can be connected to DBGrid directly, avoiding TMemTableEh, ligament DBGridEh-DataSource-
MemTableEh-DataDriverEh-DataSet is possible to use if you want to use advantages of
DBGridEh functioning in ligaments with MemTableEh such as ViewScroll mode, tree-type
viewing of data, using same data by the several MemTableEh’s.
In the mode of the supplier, TDataDriverEh takes data from DataSet that assigned to
ProviderDataSet property, and copies them in TMemTableEh. Before getting first record,
MemTableEh requests structure of fields from TDataDriverEh and create internal array of
records. TDataDriverEh build structure of fields on basis of fields list of ProviderDataSet. As
required, TDataDriverEh takes values of the current record, writes their to a new record of
TMemTableEh and goes over to the next record in ProviderDataSet.
Furthermore, TDataDriverEh can refresh values of the existing MemTable record from
ProviderDataSet (TMemTableEh.RefreshRecord method). TDataDriverEh find record in
ProviderDataSet using fields value from KeyFields property and reread values of record in
MemTable record. When TDataDriverEh is used as handler of change
(TMemTableEh.ApplyUpdates method), it takes a changed record from TMemTableEh, using
characteristic KeyFields, finds its position in ProviderDataSet, updates a record in
ProviderDataSet, queries it again from ProviderDataSet and returns a record back in
TMemTableEh.
Events of TDataDriverEh allows to control data which are transferred between
TDataDriverEh and TMemTableEh , as well as transfer and process changes from any/to other
types source of data.

TDataDriverEh have next events:


OnBuildDataStruct - write this event to change a structure of fields created when
TMemTableEh requests structure of fields. You can call DafaultBuildDataStruct method to build
a structure by default.
OnProduceDataReader - write this event to return dataset-cursor to read data. You can
call DefaultProduceDataReader method to define dataset-cursor by default. By default dataset-
cursor will be a ProviderDataSet.
OnReadRecord - write this event to assign values of record of new record that delivered to
TMemTableEh, or indicate that no more data. You can call DefaultReadRecord method to assign
values by default. By default values of record will be assigned from dataset-cursor. If Eof
function of dataset-cursor is True then TDataDriverEh indicate that no more data.
OnAssignFieldValue - write this event to assign a value of each field of new record
that is delivered to TMemTableEh, or when record is refreshing. Use DataValueVersion to
determine the mode of assigning: dvvValueEh – when need to assign value for a new record,
dvvRefreshValue - when need to assign value for existing record. You can call
DefaultAssignFieldValue to assign a value of the field by default.
OnRefreshRecord - write this event to assign fresh value of fields at the refreshment of
record from the server. You an call DefaultRefreshRecord to assign fresh values by default.
OnUpdateRecord - write this event to process updated records in TMemTableEh. Use
MemRec.UpdateStatus property to determine the type of changes: Updating, Deleting or
Inserting. You can call DefaultUpdateRecord to process updated record by default. By default
DataDriver conducts changes in ProviderDataSet.
OnUpdateError - write this event to respond certain actions when error is arising in time
of processing updates.
Following reaction is possible when error is arising:
ueaBreakAbortEh Break this and all following operations of changes, exception is not
raising.
ueaBreakRaiseEh Break this and all following operations of changes, rollback
transactions, exception is raising.
ueaCountinueEh Ignore an error, does not change a status of a record and continue a
performing the rest operations.
ueaRetryEh Repeat an operation (You should undertake actions to prevent this
error on next time).
ueaUpdated CountinueSkip Ignore an error, set record status to Unchanged,
continue a performing the rest operations.
You can call DefaultUpdateError to execute actions by default.

TSQLDataDriverEh component.
TSQLDataDriverEh is a universal DataDriver that can interact with server using SQL
commands. TSQLDataDriverEh have five objects of the TSQLCommandEh type:
SelectCommand, DeleteCommand, InsertCommand, UpdateCommand, GetrecCommand. Each
object holds SQL expressions and parameters to execute command to get table data, delete
record, insert record, update record and get one record. To execute commands
TSQLDataDriverEh calls global event - DefaultSQLDataDriverResolver.OnExecuteCommand.
You should write this event to execute SQL expressions on the server and, if need, return DataSet
to read data. When TSQLDataDriverEh is used as provider of data, it takes records from
DataSet created in DefaultSQLDataDriverResolver.OnExecuteCommand event and writes them
in TMemTableEh. On the measure of the requirement it takes given current record, writes them
in TMemTableEh and goes over to following record. When TSQLDataDriverEh is used as
handler of changes, it takes a changed record from TMemTableEh, and call
DefaultSQLDataDriverResolver.OnExecuteCommand event sending DeleteCommand,
InsertCommand or UpdateCommand as a parameter.
Using TSQLDataDriverEh it is possible change a type of the access to data. Suffice it to
rewrite global event - DefaultSQLDataDriverResolver.OnExecuteCommand.
TSQLDataDriverEh has a SpecParams property of TStrings type. You may use it to write the
special values, which you can use in the DefaultSQLDataDriverResolver.OnExecuteCommand
event. This event also is used by TServerSpecOperationsEh object when
DefaultSQLDataDriverResolver.ServerSpecOperations property is assigned. List of special
values depends of the type of TServerSpecOperationsEh object and values is filled similarly of
description in the "Characteristic TXXXDataDriverEh.SpecParams" section.
DefaultSQLDataDriverResolver.ServerSpecOperations property has a TServerSpecOperationsEh
type. This object is intended to process the special operations before or after ExecuteCommand
procedure is performed. TServerSpecOperationsEh is a base class for classes
TOracleSpecOperationsEh, TMSSQLSpecOperationsEh, TInterbaseSpecOperationsEh,
TInfromixSpecOperationsEh, TDB2SpecOperationsEh, TSybaseSpecOperationsEh and
TMSAccessSpecOperationsEh. Each Of these objects can process a SpecParams property in
particular to get values of the autoincrement fields that is generated by the server. On the name
of the class it is possible to define a type of the server, for which class is intended.
For full functioning of TSQLDataDriverEh it is necessary to write
DefaultSQLDataDriverResolver.OnExecuteCommand event to execute queries on the server and
assign DefaultSQLDataDriverResolver.ServerSpecOperations property by the object that
inherited from TServerSpecOperationsEh class. Assigning a ServerSpecOperations property
makes sense, if you execute operations of the insertion in tables that have autoincrement field (or
sequence objects).
The typical code to adjust working of TSQLDataDriverEh can be look as follows:
// Below code adjusts working of TSQLDataDriverEh components in the whole Application to access
// InderBase server via BDE Engine
uses … DataDriverEh, BDEDataDriverEh;
type
TMainForm = class(TMainForm)
Database1: TDatabase;
SQLDataDriverEh: TSQLDataDriverEh;

procedure TMainForm.FormCreate(Sender: TObject);
begin
DefaultSQLDataDriverResolver.OnExecuteCommand := OnExecuteSQLCommand;
DefaultSQLDataDriverResolver.ServerSpecOperations := TInterbaseSpecOperationsEh.Create;
end;

procedure TMainForm.FormDestroy(Sender: TObject);


begin
DefaultSQLDataDriverResolver.ServerSpecOperations.Free;
DefaultSQLDataDriverResolver.ServerSpecOperations := Nil;
end;

function TMainForm.OnExecuteSQLCommand(SQLDataDriver: TCustomSQLDataDriverEh;


Command: TCustomSQLCommandEh; var Cursor: TDataSet; var FreeOnEof,
Processed: Boolean): Integer;
begin
Result := DefaultExecuteBDECommandEh(SQLDataDriver, Command,
Cursor, FreeOnEof, Processed, Database1.DatabaseName);
end;

TSQLDataDriverEh is a base class for TBDEDataDriverEh, TIBXDataDriverEh,


TDBXDataDriverEh and TADODataDriverEh. These objects overwrite ExecuteCommand
procedure and them can execute SQL expressions on the server and if need returns DataSet to
read data. When SQL commands is called, it creates DataSet with type of corresponding type of
the access to data. For TBDEDataDriverEh it is a TQuery, for TIBXDataDriverEh it is a
TIBXQuery and so on. Furthermore, TBDEDataDriverEh, TIBXDataDriverEh,
TDBXDataDriverEh can define TServerSpecOperationsEh object automatically. For
TADODataDriverEh it is need to assign DefaultSQLDataDriverResolver. ServerSpecOperations
because ADO technology does not allow to define a type of the server.
TSQLDataDriverEh have the next events:
OnExecuteCommand - write this event to execute SQL expression. You can call
TCustomSQLDataDriverEh.DefaultExecuteCommand method to process this event by default.
By default TCustomSQLDataDriverEh. DefaultExecuteCommand calls
DefaultSQLDataDriverResolver.ExecuteCommand method, which, in turn, call
DefaultSQLDataDriverResolver.OnExecuteCommand event.
OnGetBackUpdatedValues - write this event to return updated values from server.
You can call TCustomSQLDataDriverEh.DefaultGetUpdatedServerValues method to process
action by default. TCustomSQLDataDriverEh.DefaultGetUpdatedServerValues call
DefaultSQLDataDriverResolver.GetBackUpdatedValues. If it was not processed in
DefaultSQLDataDriverResolver then it call
InternalGetServerSpecOperations.GetBackUpdatedValues. InternalGetServerSpecOperations
returns object of TServerSpecOperationsEh type.

Property TXXXDataDriverEh.SpecParams.

Property SpecParams kept a list of parameters and values. TXXXDataDriverEh use them
when performing SQL expressions. Value of each parameter have to be wrote in the separate line
in the format ‘PARAMETER_NAME =VALUE’. Depending on the type of the server
(InterBase, Oracle, MSSQL, Informix) SpecParams can contain the following parameters.

On interaction with InterBase server:


‘GENERATOR’ - defines a name of the InterBase generator. DataDriver uses this
parameter to get current value of generator after the insertion of new record.
‘GENERATOR_FIELD’ - defines a name of the field, which will be assigned current
value of the generator after the insertion of new record.
‘AUTO_INCREMENT_FIELD’ - defines a name of the field, which DataDriver will set
AutoIncremet type. It is used on making a structure of the internal array of record.

On interaction with Oracle server:


‘SEQUENCE’ - will assign a name of the field Oracle sequences. DataDriver uses this
parameter for the reception of the current value of the sequence after the insertion of new
record.
‘SEQUENCE_FIELD’ - will assign a name of the field, which will be assigned current
value of the sequence after the insertion of new record.
‘AUTO_INCREMENT_FIELD’ - defines a name of the field, which DataDriver will set
AutoIncremet type. It is used on making a structure of the internal array of record.

On interaction with MSSQL server:


‘AUTO_INCREMENT_FIELD’ - defines a name of the field, which DataDriver will set
AutoIncremet type. It is used on making a structure of the internal array of record.

On interaction with Informix server:


‘AUTO_INCREMENT_FIELD’ - defines a name of the field, which DataDriver will set
AutoIncremet type. It is used on making a structure of the internal array of record.

Example of the list of parameters for InterBase server:


GENERATOR=EMP_NO_GEN
GENERATOR_FIELD=emp_no
AUTO_INCREMENT_FIELD=emp_no

SQL expression for the insertion of record must contain EMP_NO_GEN generator.
insert into
employee (EMP_NO, FIRST_NAME)
values
(:EMP_NO_GEN, :FIRST_NAME)
TSQLDataDriverEh or TXXXDataDriverEh, which one is best to use.
As TSQLDataDriverEh as one of the TBDEDataDriverEh, TIBXDataDriverEh,
TDBXDataDriverEh or TADODataDriverEh components (we will name them as
TXXXDataDriverEh) allow to work with database without big number of tunings.
For TXXXDataDriverEh it is sufficiently to set database object property (For
TBDEDataDriverEh it is a Database property of TDatabase type).
TSQLDataDriverEh does not have database object property. To force it works is sufficiently to
write DefaultSQLDataDriverResolver.OnExecuteCommand event once to execute queries on
server, and assign DefaultSQLDataDriverResolver.ServerSpecOperations property by the object
of TServerSpecOperationsEh type to process some specific server operations.
DefaultSQLDataDriverResolver is not visual object, so you have to assign an event and property
in the program, for example in the OnCreate event of your main form. It is possible to change
access Engine to database quickly when you use TSQLDataDriverEh. It is sufficiently rewrite
global event - DefaultSQLDataDriverResolver.OnExecuteCommand only.
TSQLDataDriverEh and TXXXDataDriverEh works very similar at design-time. When
TSQLDataDriverEh component editor is opening you can choose one of design-time types of the
database accesses that built-over BDE, ADO, IBX and DBX engines. It is not necessarily that
the access engine that you use at design-time will be same as you write in
DefaultSQLDataDriverResolver.OnExecuteCommand event.

Working with TSQLDataDriverEh and TXXXDataDriverEh at design-


time.

Double click on TSQLDataDriverEh or TXXXDataDriverEh component opens a dialog editor of


TSQLDataDriverEh component. At a design-time TSQLDataDriverEh and TXXXDataDriverEh
always use design time copy of object that work with database (it is TDatabase object for DBE
engine). If where are not any object was created the system will offer to create a new object.
Type of dialog of creating DB Object depend of type of TXXXDataDriverEh. For
TSQLDataDriverEh it show dialog where you can choose a type of the access to server (Engine)
and service of data processing of server (DB Service). Type of the access defines a engine to
access the data and can be one of the following types: BDE, IBX, DBX or ADO. For ADO also
need to define "Service a data processing", class that can get a list of DB objects from server. If
object that work with database already has been create before then system will offer to choose
one of the existing.

Window of editing TSQLDataDriverEh have a next controls:


1. Tree list of DB objects. Tables, Views, Procedures, Functions etc. It depends of server
type.
2. Lower window of elements of the current object in the tree of objects.
3. Output grid of result of executing the Select expressions.
4. Page of Select expression (TSQLDataDriverEh.SelectSQL)
5. Pages expressions for Inserting, Updating, Deleting, Requesting one record.
6. Page to fill SpecParams property and parameters of dynamic SQL building.
Feedbacks and bug reports
Don't lazy to notify me about all bugs that you found. But when you send information about
errors prepare as more as possible detail info about errors. To check your information I have to
have possibility to model same errors on my computer.
Include info about OS and service pack, Version of Delphi with Build, Version of EhLib.
Also, if possible and you have suspicion that it give additional info, check that error raise on
other computers, other OS, other versions of Delphi, other versions of EhLib.
The most effective result will be if you send me source code of special demonstration Project
that raise it error. Demo Project have to have standard dataset's (not third party) and use tables
from DBDEMOS or you can copy data from your dataset to TClientDataSet. Don't send me
Demo Projects that contain third party DataSet's or other third party components.

Para criar este efeito de suavizar setar as propriedades:


Anotações Alt_C GridLinesParams.VertEmptySpaceStyle := dessGradiendEh
OptionsEh.DghExtendVertLines := True;
Formatação Grade

Se quiser esta linha vertical de separação das colunas, setar a


Propriedade GridLinesParams.DataVertLines := True

Para criar este efeito de truncar a grade, setar as propriedades:


GridLinesParams.VertEmptySpaceStyle := dessNonEh
OptionsEh.DghExtendVertLines := false;
Obs.: Se setar DghExtendVertLines como false o valor na
propriedade VertEmptySpaceStyle será trocada para dessNonEh

Se quiser esta linha de borda horizontal de fechamento da grade, setar


a Propriedade GridLinesParams.GridBondaries := True
Se quiser esta linha horizontal de separação das linhas, setar a
Propriedade GridLinesParams.DataHorzLines := True

Para estender a continuação da grade para adaptar à janela, poderá ser feito de 3
formas :
Não extender, - deshNonEh
Estender com linhas - deshExtendGridWideSpaceEh
ou Estender somente o Título - deshExtendTitleWideSpaceEh
O efeito acima foi feito setando a propriedades :
GridLinesParams.HorzEmptySpaceStyle := deshExtendTitleWideSpaceEh
OptionsEh.DghExtendVertLines := false;
Obs.: Se setar DghExtendVertLines como false o valor na propriedade
VertEmptySpaceStyle será trocada para dessNonEh

Botão Edição Coluna

Para inserir um botão em uma coluna (EditButton) desejada deverá seguir os passos abaixo:
 Procurar a propriedade EditButton e setar as sub propriedades;
 DefaultAction para true;
 Enabled para true;
 Visible para true;
 Style escolher ebsEllipsisEh;

Depois que selecionou o botão e o mesmo já esta sendo exibido na linha da grade, deverá criar os
procedimentos que serão executados ao se clicar no botão, e para isto no gatilho de disparo do
evento onEditButtnClic faça a rotina a ser executada.
Obs.: Não esqueça de setar o parâmetro Handled para True no inicio dos procedimentos, para
indicar que você mesmo deseja fazer a atualização dos dados,

You might also like