EhLib Users Guide
EhLib Users Guide
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.
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.
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
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:
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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';
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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:
It set new object of management and returns the old object. The Old object, in most cases, is
required to destroy.
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.
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.
// 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);
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.
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:
Call this function to set new object of image controlling. It returns old object. In most cases it is
necessary to delete old object.
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.
FAQ List:
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:
TDBSumList is embedded in DBGridEh component, so that all below text in equal degrees
pertains as to TDBSumList component and to TDBGridEh.SumList property.
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.
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.
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.
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.
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).
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:
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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;
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.
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.
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
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,