TMSFNCGrid
Introduction
The TMS FNC Grid offers a fully cross-platform, high-performing, versatile and feature packed grid. It is built from the ground up and at the same time, it is sufficiently similar to the VCL TAdvStringGrid to make developers used to TAdvStringGrid quickly familiar and up & running
Grid properties
Property name | Description |
---|---|
ColumnCount | integer: Gets or sets the number of columns displayed in the grid. |
Columns | TTMSFNCGridColumns: A collection of columns to allow designtime / runtime customization and persistence of grid cell layout / types and behavior such as sorting and editing. More information about the columns collection can be found in the “Columns” chapter. |
DefaultColumnWidth | single: The default width of a column. When new columns are added to the grid, the width will default to this value. The width of a column can be changed per column with grid.ColumnWidths[ACol]: single. |
DefaultRowHeight | single: The default height of a row. When new rows are added to the grid, the height will default to this value. The height of a row be changed per row with grid.RowHeights[ARow]: single. |
FixedColumns | integer: Gets or sets the amount of fixed columns in the grid. Fixed columns are columns that remain visible at all times, that do not scroll along with the grid when scrolling horizontal and that get a separate appearance, the fixed cell appearance. |
FixedFooterRows | Integer: Gets or sets the amount of fixed footer rows. Footer rows are rows that are positioned at the bottom side of the grid, remain visible at all times, do not scroll along with the grid when scrolling vertical and that get a separate appearance, the fixed cell appearance. |
FixedRightColumns | Integer: Gets or sets the amount of fixed right columns. Right columns are columns which are positioned at the right side of the grid, remain visible at all times and do not scroll along with the grid when scrolling horizontal. |
FixedRows | Integer: Gets or sets the amount of fixed rows in the grid. Fixed rows are rows which remain visible at all times and do not scroll along with the grid when scrolling vertical. |
LeftCol | Integer: Gets or sets the index of the first visible normal column that is selectable. Use this property to programmatically control the horizontal scroll position in the grid. |
Options | The various options available in the grid. (Explained in “Options” chapter) |
RowCount | Integer: Gets or sets the amount of rows in the grid. |
ScrollMode | TTMSFNCGridScrollMode: Gets or sets the type of scrolling. There are 2 types of scrolling: cellscrolling and pixelscrolling. With cellscrolling is selected, the scrolling is based on entire columns or rows. A complete row or column is moved depending on the scroll direction. With pixelscrolling is selected, the scrolling is based on the total width and height of the cells allowing you to scroll more precisely and having cells partially visible. |
TopRow | Integer: Gets or sets the first normal visible row that is selectable. This property can be used to programmatically control the vertical scroll position in the grid. |
UseColumns | Boolean: public property used to toggle between persisted column data through the columns collection at designtime/runtime (UseColumns = true) or dynamically created data at runtime (UseColumns = false). More information about the Columns collection can be found in the “Columns” chapter. |
Organisation
In its basic layout, a grid is a matrix of cells with mainly fixed cells (not editable) and normal cells. A fixed cell will not scroll along with normal cells and thus remain visible on any of the 4 sides of the grid. This number of fixed rows and/or columns on the 4 sides of the grid is controlled by properties: grid.FixedRows, grid.FixedColumns, grid.FixedFooterRows, grid.FixedRightColumns. In addition to fixed, non scrolling rows and/or columns, the grid can also perform column freezing. These are columns or rows of normals cells that will not scroll along with the other columns or rows in the grid. The number of freeze columns and rows is set with grid.FreezeColumns, grid.FreezeRows. Cells are accessible via grid.Cells[Column,Row]:string and the selected cell(s) can be set with properties:
grid.Selection := MakeCellRange(StartCol,StartRow,EndCol,EndRow);
grid.FocusedCell := MakeCell(Col,Row);
This automatic scrolling and some additional properties to control speed and interval can be set under grid.Options.Mouse.
The size of columns & rows is controlled by grid.ColumnWidths[ColumnIndex]: single, grid.RowHeights[RowIndex]: single and it can be configured that the user can resize columns or rows at runtime with: grid.Options.Mouse.ColumnSizing, grid.Options.Mouse.FixedColumnSizing, grid.Options.Mouse.RowSizing, grid.Options.Mouse.FixedRowSizing.
The amount of displayed columns and rows are set with grid.ColumnCount: integer and grid.RowCount: integer properties.
Rows and columns can be inserted / deleted by pressing the Insert / Delete key on the keyboard. Note that when a row is inserted or deleted from the user interface, the events OnCanInsertRow, OnInsertRow, OnCanDeleteRow,OnDeleteRow are triggered. The OnCanInsertRow, OnCanDeleteRow events occur before the actual insert or delete happens and have the extra parameter Allow: Boolean that can be set to false to disallow a specific row insert or delete.
Programatically, following methods are available inserting, deleting columns or rows but also to move and swap columns or rows:
grid.InsertRow(ARow: integer): insert a new row at row ARow
grid.InsertRows(ARow, NumRows: integer): insert NumRows rows at row ARow
grid.DeleteRow(ARow: integer) : remove row with index ARow from the grid
grid.DeleteRows(ARow, NumRows: integer): remove NumRows rows at row ARow.
grid.InsertColumn(ACol: integer): insert a new column at column ACol
grid.DeleteColumn(ACol: integer): remove column with index ACol from the grid
grid.MoveRow(FromRow, ToRow: integer): move row from index FromRow to index ToRow
grid.MoveColumn(FromCol, ToCol: integer): move column from index FromCol to index ToCol
grid.SwapRows(Row1,Row2: integer): swap content of Row1 and Row2
grid.SwapColumns(Col1,Col2: integer): swap content of Col1 and Col2
The keyboard interaction can be modified with the grid.Options.Keyboard.InsertKeyHandling
and grid.Options.Keyboard.DeleteKeyHandling properties.
Cell Properties
Property name | Description |
---|---|
Cells[Col,Row: Integer]: string | Sets the text of a cell. Col & row are the visual column & row coordinates of the cell. ![]() |
Floats[Col,Row: Integer]: double | Gets or sets the value of a cell as a double. |
AllCells[Col,Row: Integer]: string | Similar behavior as Cells[Col, Row: Integer]: TCellData This accesses the cells with column & row coordinates irrespective of column or row hiding. Coordinates are real column, row coordinates. |
StrippedCells[Col,Row: Integer]: string | Returns the text of a cell with all HTML formatting removed. |
AllFloats[Col,Row: Integer]: double | Gets or sets the value of a cell as a double. This accesses the cells with column & row coordinates irrespective of column or row hiding where grid.Floats[Col,Row] access the value based on displayed cell coordinates. ![]() |
ColumnWidths[Col: Integer]: single | Gets or sets the width of a column. When no column width is set for a column, the width is set to DefaultColumnWidth. ![]() |
RowHeights[Row: Integer]: single | Gets or sets the height of a row. When no row height is set for a row, the height is set to DefaultRowHeight ![]() |
Events
Custom Cell Drawing
Each cell supports custom drawing via an event and with event parameters to optionally disable the background, text, as well as a reference to the Canvas and the rectangle. With the events OnCellBeforeDraw and OnCellAfterDraw you can custom draw on a cell, or complete column / row of choice that can be retrieved by using the Row and Column parameters. Below is a sample that draws a diagonal line as a background which replaces the default background of a cell on location 3, 3.
procedure TForm135.TMSFNCGrid1CellAfterDraw(Sender: TObject; ACol,
ARow: Integer; AGraphics: TTMSFNCGraphics; ARect, ATextRect:
TRectF);
begin
if (ACol = 3) and (ARow = 3) then
begin
AGraphics.SetStrokeColor(gcRed);
AGraphics.DrawLine(PointF(ARect.Left, ARect.Top),
PointF(ARect.Right, ARect.Bottom));
end;
end;
Custom Cell Class
When dropping a default grid on the form, you will notice fixed and normal cells. The basic implementation supports a fill, stroke and a text. For a normal default cell, the cell class type is TTMSFNCGridCell. A fixed cell implements and inherits all features from the base cell and adds the possibility to add controls that will help you in terms of filtering, checking a complete column or additional functionality that you can provide with the various events that are implemented. The fixed cell class is TTMSFNCFixedGridCell and is used when the grid detects a cell is fixed. The default grid cell can be changed to a different type through events or with the correct procedures in the grid. The grid cell already supports a number of different classes that are listed below.
The cell class type can be set dynamically via the event OnGetCellClass or various methods are provided to set this programmatically. The grid already offers a number of predefined cell classes for the most common uses and events like OnGetCellLayout can deal with these built-in classes to properly set cell properties as color, font, alignment. When using a class type not known to the grid, it will be required to dynamically control properties such as color, font, etc… via the OnGetCellProperties and cast the parameter Cell: TTMSFNCGridCell to the type specified for the cell.
Example: specifies that a checkbox is used for column 3:
procedure TForm4.TMSFNCGrid1GetCellClass(Sender: TObject; ACol, ARow:
Integer;
var CellClassType: TTMSFNCGridCellClass);
begin
if (ARow >= TMSFNCGrid1.FixedRows) and (ACol = 3) then
CellClassType := TTMSFNCCheckGridCell;
end;
var
i: integer;
begin
for i := TMSFNCGrid1.FixedRows to TMSFNCGrid1.RowCount - 1 do
TMSFNCGrid1.AddCheckBox(3,i,false);
end;
procedure TForm1.TMSFNCGrid1GetCellProperties(Sender: TObject; ACol,
ARow: Integer; Cell: TTMSFNCGridCell);
begin
if (ACol = 3) and (ARow >= TMSFNCGrid1.FixedRows) and (Cell is
TTMSFNCCheckGridCell) then
begin
(Cell as TTMSFNCCheckGridCell).CheckBox.IsChecked := true;
end;
end;
TTMSFNCGridCell
Basic implementation of a grid cell, with a fill, stroke and text properties.
TTMSFNCRadioGridCell
Inherits from TTMSFNCGridCell and adds the capability to display a radiobutton.
The methods to add & remove radiobuttons are:
Method name | Description |
---|---|
TMSFNCGrid.AddRadioButton(Col,Row,Index: integer; State: boolean = false); | Adds a radiobutton in cell Col,Row belonging to group Index. The State parameter sets the default state of the radiobutton. |
TMSFNCGrid.AddRadioButtonColumn(Col,Index: integer); | Adds a column of radiobuttons as group Index |
TMSFNCGrid.RemoveRadioButton(Col,Row: integer); | Removes the radiobutton from cell Col,Row |
TMSFNCGrid.IsRadioButton(Col,Row: integer): boolean; | Returns true when the cell contains a radiobutton |
TMSFNCGrid.RadioButtonState(Col,Row: integer): boolean; | Returns the state of a radiobutton in cell Col,Row |
Index parameter | The index of a radio group to which the radiobutton belongs |
State parameter | Sets the radiobutton in a checked or unchecked state. |
Examples:
TTMSFNCCheckGridCell
Inherits from TTMSFNCGridCell and adds the capability of displaying a checkbox.
The methods to add & remove checkboxes are:
Method name | Description |
---|---|
TMSFNCGrid.AddHeaderCheckBox(Col,Row: integer; State: boolean = false); | Adds a checkbox in a fixed column header cell. A column header checkbox will toggle the checkbox state of all checkboxes in a column when it is clicked. |
TMSFNCGrid.AddCheckBox(Col,Row: integer; State: boolean = false); | Add a checkbox to cell Col,Row. |
TMSFNCGrid.AddCheckBoxColumn(Col: integer); | Add checkboxes in all cells of column Col. |
TMSFNCGrid.RemoveCheckBox(Col,Row: integer); | Remove the checkbox in cell Col,Row. |
TMSFNCGrid.IsCheckBox(Col,Row: integer): boolean; | Returns true when the cell Col,Row contains a checkbox. |
TMSFNCGrid.CheckBoxState[Col,Row: integer]: boolean | Gets or sets the checkbox state of cell Col,Row |
TMSFNCGrid.AddDataCheckBox(Col,Row: integer; State: boolean = false); | Adds a data checkbox to cell Col,Row. A data checkbox cell is a cell with a checkbox where the checked state of the checkbox reflects the text value of the cell. When the text value of the cell equals TMSFNCGrid.CheckTrue, it will be displayed as checked. When the text value of the cell equals TMSFNCGrid.CheckFalse, it will be displayed as unchecked. To get or set the checkbox state of this checkbox type, use: TMSFNCGrid.Cells[Col,Row] := TMSFNCGrid.CheckTrue. or if TMSFNCGrid.Cells[Col,Row] = TMSFNCGrid.CheckTrue then // checkbox is true TMSFNCGrid.AddDataCheckBoxColumn(Col: integer); Adds data checkboxes in all cells of column Col. |
Examples:
TTMSFNCProgressGridCell
Inherits from TTMSFNCGridCell and adds the capability of displaying a progressbar.
Progressbar values are between 0 and 100.
The methods to add & remove progress bars in the grid are:
Method name | Description |
---|---|
TMSFNCGrid.AddProgressBar(Col,Row: Integer; Value: Single); | Adds a progress bar with position Value in the grid cell Col,Row. |
TMSFNCGrid.AddButton(Col,Row: Integer; AText: string; AWidth: Integer = 20; AHeight: Integer = 20); | Adds a button with a specific text, width and height. Generates the OnCellButtonClick event when clicked. |
TMSFNCGrid.AddDataProgressBar(Col,Row: Integer); | Adds a data progress bar in the grid cell Col,Row. The value of the progressbar is controlled by the value set in grid.Cells[Col,Row]. |
TMSFNCGrid.SetProgressBarValue(Col,Row: Integer; Value: single); | Sets the value of a progressbar in cell Col,Row. |
TMSFNCGrid.GetProgressBarValue(Col,Row: integer): single; | Retrieves the value of a progressbar in cell Col,Row |
TMSFNCGrid.IsProgressBar(Col,Row: Integer): boolean; | Returns true when cell Col,Row contains a progress bar |
TMSFNCGrid.RemoveProgressBar(Col,Row: Integer); | Removes the progressbar from cell Col,Row. |
Examples:
TTMSFNCCommentGridCell
Inherits from TTMSFNCGridCell and adds the capability of display a comment in a popup. Also adds an indicator in the topright corner.
The comment text and comment indicator triangle color can also be controlled by properties:
When the comment text is an empty string, no comment triangle will be displayed.Examples:
TMSFNCGrid1.Comments[1, 1] := ‘Hello World!’;
TMSFNCGrid1.CommentColors[1, 1] := gcRed;
TMSFNCGrid1.Comments[2, 2] := ‘’; // remove comment from cell 2,2
TTMSFNCFixedGridCell
Inherits from TTMSFNCGridCell and adds several capabilities such as showing a sorting indicator, a filter dropdown button, a column header checkbox.
TTMSFNCNodeGridCell
Inherits from TTMSFNCGridCell and adds the capability of displaying a node with which several rows can be collapsed or expanded.
The methods to deal with nodes in the grid are:
Method name | Description |
---|---|
TMSFNCGrid.AddNode(Row, Span: Integer); | Adds a node that spans Span rows in cell 0,Row. |
TMSFNCGrid.RemoveNode(Row: Integer); | Removes a node from cell 0,Row. |
TMSFNCGrid.IsNode(Row: Integer): boolean; | Returns true when cell 0,Row contains a node. |
TMSFNCGrid.SetNodeState(Row: Integer; State: TNodeState); | Sets the state of the node in cell 0,Row as opened or closed. TNodeState = (nsClosed, nsOpen); |
TMSFNCGrid.GetNodeState(Row: integer): TNodeState; | Returns the state of a node in cell 0,Row with TNodeState = (nsClosed, nsOpen); |
TMSFNCGrid.SetNodeSpan(Row: Integer; Span: Integer); | Changes the number of rows a node at cell 0,Row spans. |
TMSFNCGrid.GetNodeSpan(Row: Integer): Integer; | Retrieves the number of rows a node spans. |
TMSFNCGrid.GetNode(Row: Integer): TCellNode; | Gets the node object used in cell 0,Row. |
TMSFNCGrid.OpenNode(Row: Integer); | Opens (expands) all rows within the span of node at cell 0,Row. |
TMSFNCGrid.CloseNode(Row: Integer); | Closes (collapses) all rows within the span of node at cell 0,Row. |
TMSFNCGrid.OpenAllNodes; | Opens all nodes in the grid. |
TMSFNCGrid.CloseAllNodes; | Closes all nodes in the grid. |
TTMSFNCBitmapGridCell
Inherits from TTMSFNCGridCell and adds the capability of displaying a bitmap.
The methods to deal with cell bitmaps in the grid are:
Method name | Description |
---|---|
TMSFNCGrid.AddBitmap(Col,Row: Integer; AName: string); | Adds a bitmap with name AName from the assigned BitmapContainer to cell Col,Row |
TMSFNCGrid.AddBitmap(Col,Row: Integer; ABitmap: TBitmap); | Adds a bitmap instance ABitmap to cell Col,Row |
TMSFNCGrid.AddBitmapFile(Col,Row: Integer; AFileName: string); | Adds a bitmap from file AFileName to cell Col,Row |
TMSFNCGrid.CreateBitmap(Col,Row: Integer): TBitmap; | Creates a new bitmap instance that is added to cell Col,Row. The bitmap instance can be used to load images from another source. |
TMSFNCGrid.AddDataBitmap(Col,Row: Integer); | Adds a data bitmap to cell Col,Row. The bitmap that will be displayed in the cell will depend on the text value in the cell that is used as name in the assigned BitmapContainer |
TMSFNCGrid.RemoveBitmap(Col,Row: Integer); | Remove the bitmap from cell Col,Row. |
TMSFNCGrid.IsBitmap(Col,Row: integer): boolean; | Returns true when the cell Col,Row contains a bitmap. |
TMSFNCGrid.GetBitmap(Col,Row: integer): TBitmap; | Returns the bitmap instance in cell Col,Row. |
TMSFNCGrid.SetBitmapName(Col,Row: integer; AName: string); | Sets/updates the name of the bitmap referring to the assigned BitmapContainer that was added before with the method AddBitmap() |
TMSFNCGrid.GetBitmapName(Col,Row: integer): string; | Returns the name of a bitmap referring to the assigned BitmapContainer. |
Grid cell merging / splitting
The grid supports merging and splitting cells programmatically as well as with the keyboard. To merge a range of cells simple call
Sample:To split the merged cells, you can use the procedure grid.SplitCell. The parameters passed in the procedure need to be the base cell of the range of merged cells.
Sample:
When enabled via grid.Options.Keyboard.AllowCellMergeShortCuts, the following shortcuts invoke a merge & split of the selected cells:Editing
By default the grid supports editing, this can be turned on and off with grid.Options.Editing.Enabled. The default editor is a TTMSFNCEdit which is an control descending from TEdit and that adds a range of new features that offer a more user-friendly experience for grid editing.
To start editing, click on a selected cell to display the inplace editor or press F2 or start typing any key:
Under grid.Options.Keyboard, grid.Options.Mouse, grid.Options.Editing there are various properties that can be used to customize the way the editing occurs, from direct editing to navigating from edit to edit with the arrow keys, as well as enterkeyhandling to jump to the next row or column, … .
These are the different type of editors available in the grid:
etEdit, etNumericEdit, etSignedNumericEdit, etFloatEdit, etSignedFloatEdit, etUppercaseEdit, etMixedCaseEdit, etLowerCaseEdit, etMoneyEdit, etHexEdit, etAlphaNumericEdit, etValidCharsEdit, etComboBox, etSpinBox, etDatePicker, etColorPicker, etTrackBar, etMemo, etCustom.
To change an editor type for a specific cell, column or row, implement the OnGetCellEditorType event:
procedure TForm1.TMSFNCGrid1GetCellEditorType(Sender: TObject; ACol,
ARow: Integer; var CellEditorType: TTMSFNCGridEditorType);
begin
if (ACol = 4) and (ARow = 3) then
CellEditorType := etColorPicker;
end;
Choosing a color will automatically access the grid.Colors to set the background color of the cell:
The possibility exists to use a custom editor. To implement this, etCustom must be set to the var parameter in the OnGetCellEditorType event. For this sample we have used a TTreeView item in a cell that has a modified columnwidth and rowheight:
TMSFNCGrid1.ColumnWidths[4] := 150;
TMSFNCGrid1.RowHeights[4] := 100;
procedure TForm1.TMSFNCGrid1GetCellEditorType(Sender: TObject; ACol,
ARow: Integer; var CellEditorType: TTMSFNCGridEditorType);
begin
CellEditorType := etCustom;
end;
procedure TForm1.TMSFNCGrid1GetCellEditorCustomClassType(Sender:
TObject;
ACol, ARow: Integer; var CellEditorCustomClassType:
TTMSFNCGridEditorClass);
begin
CellEditorCustomClassType := TTreeView;
end;
procedure TForm1.TMSFNCGrid1GetCellEditorProperties(Sender: TObject;
ACol,
ARow: Integer; CellEditor: TTMSFNCGridEditor);
var
tParent, tGroup, tItem: TTreeViewItem;
begin
tParent := TTreeViewItem.Create(CellEditor);
tParent.Text := 'Fruits';
CellEditor.AddObject(tParent);
tGroup := TTreeViewItem.Create(CellEditor);
tGroup.Text := 'Red Fruits';
tParent.AddObject(tGroup);
tItem := TTreeViewItem.Create(CellEditor);
tItem.Text := 'StrawBerry';
tGroup.AddObject(tItem);
tItem := TTreeViewItem.Create(CellEditor);
tItem.Text := 'Cherry';
tGroup.AddObject(tItem);
tGroup := TTreeViewItem.Create(CellEditor);
tGroup.Text := 'Green Fruits';
tParent.AddObject(tGroup);
tItem := TTreeViewItem.Create(CellEditor);
tItem.Text := 'Apple';
tGroup.AddObject(tItem);
tItem := TTreeViewItem.Create(CellEditor);
tItem.Text := 'Lime';
tGroup.AddObject(tItem);
end;
In the OnCellEditDone event, we can set the cell text to the selected item text of the treeview.
procedure TForm1.TMSFNCGrid1CellEditDone(Sender: TObject; ACol, ARow:
Integer;
CellEditor: TTMSFNCGridEditor);
begin
TMSFNCGrid1.Cells[ACol, ARow] := (CellEditor as
TTreeView).Selected.Text;
end;
Intercepting the value from and setting the value in the edit can be done with the OnCellEditGetData, OnCellEditSetData and OnCellEditValidateData.
With the OnCellEditGetData, the data can be intercepted that is passed from the cell to the edit box to set a different text, or append additional text to the cellstring.
procedure TForm1.TMSFNCGrid1CellEditGetData(Sender: TObject; ACol,
ARow: Integer; CellEditor: TTMSFNCGridEditor; var CellString:
string);
begin
CellString := 'hello world !';
end;
When the editing is finished the OnCellEditValidateData is called, which can be used to allow / disallow the value to be added in the cell or make additional modifications before the cellstring is allow to be inserted in the cell.
After the validation is true, the OnCellEditSetData is called, which actually inserts the data in the cell. Again, the cellstring can be modified before the string is inserted in the cell.
Editing can be started by calling grid.Edit. The Focused cell will then be set in edit mode and the chosen editor will be shown. To stop editing call grid.StopEdit to persist the value in the cell or call grid.CancelEdit to revert the value back to the value before editing started.
Selection
The selection in the grid is controlled by the property TTMSFNCGrid.Options.Selection.Mode. This property determines how cells can be selected in the grid with the mouse and keyboard. The selection varies from single to multiple cells, column and row selections, disjunct selections.
smNone: Hides selection, all other interaction remains active
smSingleCell: Selects a single cell. When changing selection, the previous cell state returns to normal.
smSingleRow: Selects a complete row. When changing selection, the previous row state returns to normal.
smSingleColumn: Selects a complete column. When changing selection, the previous column state returns to normal.
smCellRange: Enables selecting multiple cells. When performing a shift-click, the range between the previous cell and current cell is selected. A range of cells can also be selected when holding and dragging the mouse over the grid.
smRowRange: Enables selecting multiple rows. When performing a shift-click, the range between the previous row and current row is selected. A range of rows can also be selected when holding and dragging the mouse over the grid.
smColumnRange: Enables selecting multiple columns. When performing a shift-click, the range between the previous column and current column is selected. A range of columns can also be selected when holding and dragging the mouse over the grid.
smDisjunctRow: Has the same functionality as smRowRange, and with the ability to distinct select rows with the ctrl key.
smDisjunctColumn: Has the same functionality as smColumnRange and with the ability to distinct select columns with the ctrl key.
smDisjunctCell: The ability to distinct select cells with the ctrl key.
For the selection modes smSingleCell, smSingleRow, smSingleColumn, smCellRange, the property grid.Selection: TCellRange gets or sets the current selected cells. To select for example in the mode smCellRange the cells range 2,2 to 4,4, this can be programmatically set with:
To select a single cell in the mode smSingleCell, the selected cell can be set with: When the Options.Selection.Mode property is smDisjunctRow, two ways are possible to get and set the selected rows:With this property, the selected state of row RowIndex is get or set. A possible way to test for all selected rows as such is:
var
i: integer;
begin
for i := 0 to TMSFNCGrid1.RowCount - 1 do
begin
if TMSFNCGrid1.RowSelect[i] then
// do something with the selected row
end;
end;
An alternative way to get the list of selection rows is by looping through grid. RowSelectionCount and check the index of the selected row returned with grid.
The code to handle this is:
var
i: integer;
begin
for i := 0 to TMSFNCGrid1.RowSelectionCount - 1 do
begin
rowindex := TMSFNCGrid1.SelectedRow[i];
// do something with the selected row rowindex here
end;
end;
Finally, for the selection mode smDisjunctCell, the selection state of a particular cell is returned with grid.CellSelect[col,row: integer]: Boolean; The total number of selected cells is returned via grid.CellSelectionCount: integer and it is also possible to loop through the list of all selected cells via grid.SelectedCell[Index: integer]: TCell. In this case, to loop through all selected cells becomes:
var
i: integer;
c: TCell;
begin
for i := 0 to TMSFNCGrid1.CellSelectionCount - 1 do
begin
c := TMSFNCGrid1.SelectedCell[i];
// do something with the selected cell
TMSFNCGrid1.Cells[c.Col, c.Row] := TMSFNCGrid1.Cells[c.Col, c.Row] + '*';
end;
end;
fcsAll: Enables clicking on the left top most fixed cell and selects all cells in the grid in combination with smCellRange.
fcsRow: Enables clicking and dragging on the fixed columns / fixed right columns in combination with smSingleRow.
fcsColumn: Enables clicking and dragging on the fixed rows / fixed footer rows in combination with smSingleColumn.
fcsRowRange: Enables clicking and dragging on the fixed columns / fixed right columns in combination with smRowRange.
fcsColumnRange: Enables clicking and dragging on the fixed rows / fixed footer rows in combination with smColumnRange.
If columndragging, rowdragging or sorting is enabled, the fixed cell selection mode is automatically disabled.
Calculations
The grid has built-in methods to perform calculations. Functions are available to perform calculations on all rows or a selected range of rows within a column. These functions generate a result when called. Another type of built-in calculations are column calculations for which the result is displayed in a footer row and for which results are updated as soon as a cell’s value changes through editing.
Built-in column calculation functions:
TMSFNCGrid.ColumnSum(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1): Double; Calculate the sum of values in a column. By default, the sum of all normal cell values is calculated. When the FromRow/ToRow parameters are used, a selected range of rows can be choosen.
TMSFNCGrid.ColumnAvg(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1): Double;
Calculates the average cell value of cells within a column.
TMSFNCGrid.ColumnMin(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1): Double;
Calculates the minimum cell value of cells within a column.
TMSFNCGrid.ColumnMax(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1): Double;
Calculates the maximum cell value of cells within a column.
TMSFNCGrid.ColumnDistinct(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1):
Double;
Counts the number of distinct cell valuess within a column.
TMSFNCGrid.ColumnStdDev(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1):
Double;
Calculates the number of standard deviation of cell values within a column.
TMSFNCGrid.ColumnCustomCalc(ACol: integer; FromRow: integer = -1; ToRow: Integer = -1):
Double;
Performs a custom calculation of values in a column. Calling this method triggers the event
OnColumnCalc that should return a result via the var parameter Res.
ccMax: column’s maximum value should be displayed in the fixed footer cell ccCUSTOM: a custom column calculation result should be displayed in the fixed footer cell ccDistinct: number of distinct values in the column should be displayed in the fixed footer cell
ccStdDev: column standard deviation should be displayed in the fixed footer cell When the cell values are updated programmatically, the column calculations can be programmatically updated for one column or for all columns. This can be done with:
Example:The grid is initialized with:
begin
TMSFNCGrid1.RowCount := 20;
TMSFNCGrid1.FixedFooterRows := 1;
TMSFNCGrid1.RandomFill(false,100);
TMSFNCGrid1.ColumnCalculation[1] := ccSUM;
TMSFNCGrid1.ColumnCalculation[2] := ccAVG;
TMSFNCGrid1.ColumnCalculation[3] := ccMIN;
TMSFNCGrid1.ColumnCalculation[4] := ccMAX;
TMSFNCGrid1.UpdateCalculations;
end;
When performing editing in the grid cells, the column calculations in the fixed footer row will be automatically updated.
Import / Export
The grid can save and load its data in many different formats explained here:
internal: Saves and loads grid cell data and column widths in a proprietary format CSV: Saves and loads grid cell data in comma separated file XLS: Saves and loads grid cell data to an Excel file (Windows and macOS only) XML: Saves the grid cell data to XML file PDF: Saves the grid cell data to PDF file ASCII: Saves cell data to ASCII file Fixed: Saves and loads the cell data to fixed length column text files HTML Saves the cell data to a HTML file stream: Saves and loads cell data to a stream
Files
procedure SaveToFile(FileName: String; Unicode: boolean = true);
procedure LoadFromFile(FileName: String);
Streams
SaveToStream saves cell data and column widths to a stream. LoadFromStream loads cell data and column widths from a stream.Example: copying grid information from grid 1 to grid 2 through a memorystream:
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
Grid1.SaveToStream(ms);
ms.Position := 0; // reset stream pointer to first position
Grid2.LoadFromStream(ms);
ms.Free;
end;
CSV files
procedure SaveToCSV(FileName: String; Unicode: boolean = true);
procedure LoadFromCSV(FileName: String; MaxRows: integer= -1);
procedure AppendToCSV(FileName: String);
procedure InsertFromCSV(FileName: String; MaxRows: integer= -1);
SaveToCSV saves cell data to a CSV file. LoadFromCSV loads cell data from a CSV file. AppendToCSV appends cell data to an existing CSV file. InsertFromCSV inserts cell data loaded from the CSV file as extra rows in the grid. Note that LoadFromCSV & InsertFromCSV have a default parameter MaxRows. Without this parameter, all rows in the CSV file are loaded in the grid. When the 2nd parameter MaxRows is used, this sets the maximum number of rows that will be loaded.
Several properties affect the CSV methods:
This specifies the delimiter to use for saving and loading with CSV files. By default the Delimiter is set to #0. With Delimiter equal to #0, an automatic delimiter guess is used to load data from the CSV file. To save to a CSV file, the ; character is used as separator when delimiter is #0. Setting the delimiter to another character than #0 forces the CSV functions to operate with this delimiter only. When true, an empty cell in the CSV file is saved as “”, otherwise no characters are written to the CSV file. Grid.Options.IO.AlwaysQuotes: Boolean; When true, every cell value is saved with prefix and suffix quotes, otherwise quotes are only used if the cell data contains the delimiter character. Note that when the cell data contains quotes, the data is written with doubled quotes to the file.By default, when loading data in the grid, data is being loaded from the first normal cell, i.e. by default this is cell 1,1 (as by default there is one fixed row and one fixed column). To override this default behavior and make the grid load data at any arbitrary cell, this can be done with the public property
As such, to start loading data from the first cell 0,0, set before calling the LoadFromCSV method.Fixed column width text files
procedure SaveToFixed(FileName: string;positions: TIntList);
procedure LoadFromFixed(FileName:string;positions:TIntList; DoTrim: boolean = true; MaxRows: integer = -1);
Example: loading from a fixed file
var
Il: TIntList;
begin
Il := TIntList.Create(0,0);
Il.Add(0); // first column offset
Il.Add(15); // second column offset
Il.Add(30); // third column offset
Il.Add(40); // fourth column offset
Grid.LoadFromFixed(“myfile.txt‟,il);
Il.Free;
end;
HTML files
SavetoHTML saves the cell data to a HTML file and uses the grid.Options.HTML for various settings that control the export. The cell data is saved to a HTML table. AppendToHTML appends the cell data to an existing HTML file.
PDF Files
Drop a TTMSFNCGridPDFIO component on the form and connect the TTMSFNCGrid to this non-visual component’s Grid property.
Export
Simply call:
Alternatively the TMSFNCGridPDFIO component is able to save to a stream. Simply call the Save method with a TStream instance. Additionally, the TMSFNCGridPDFIO component is capable of configuring the margins, header, footer as well as PDF meta-data such as the creator, author title and keywords. These properties are found under Options and Information.XML files
Saves the cell data in an XML file with following structure:<ListDescr>
<RecordDescr>
<FieldDescr[0]>Cell 0,0</FieldDescr[0]>
<FieldDescr[1]>Cell 1,0</FieldDescr[1]>
<FieldDescr[2]>Cell 2,0</FieldDescr[2]>
</RecordDescr>
<RecordDescr>
<FieldDescr[0]>Cell 0,1</FieldDescr[0]>
<FieldDescr[1]>Cell 1,1</FieldDescr[1]>
<FieldDescr[2]>Cell 2,1</FieldDescr[2]>
</RecordDescr>
</ListDescr>
This code snippet save a grid with 5 columns to XML and uses the text in the column headers as field descriptors in the XML file:
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
for i := 0 to grid.ColCount – 1 do
sl.Add(grid.Cells[I,0]);
grid.SaveToXML(„mygrid.xml‟, „xmllist‟, „xmlrecord‟, sl);
sl.Free;
end;
ASCII files
SaveToASCII saves the cell data to an ASCII file, automatically using column widths to fit the widest data in cells available. A difference with fixed column width files is also that SaveToASCII will correctly split cell contents across multiple lines. AppendToASCII is identical to SaveToASCII, except that it appends the data to an existing file.XLS files (Windows and macOS only)
With the TTMSFNCGridExcelIO component directly reading and writing Excel .XLS files without the need to have Excel installed on the machine is easier than ever.
To use TTMSFNCGridExcelIO for XLS file import or export, follow these steps:
-
drop TTMSFNCGrid on a form as well as the component TTMSFNCGridExcelIO
-
Assign the instance of TTMSFNCGrid to the Grid property of the TTMSFNCGridExcelIO component
-
You can set TTMSFNCGridExcelIO properties to control the Excel file read / write behaviour but in most cases default settings will be ok.
- To import an Excel file, use:
TMSFNCGridExcelIO.XLSImport(FileName); or TMSFNCGridExcelIO.XLSImport(FileName,SheetName); To export the contents of TTMSFNCGrid to an XLS file use:
orProperties of TTMSFNCGridExcelIO
Many properties are available in TTMSFNCGridExcelIO to customize importing & exporting of Excel files in the grid.
Property name | Description |
---|---|
AutoResizeGrid: Boolean; | When true, the dimensions of the grid (ColCount, RowCount) will adapt to the number of imported cells. |
DateFormat: string; | Sets the format of dates to use for imported dates from the Excel file. When empty, the default system date formatting is applied. |
GridStartCol, GridStartRow: integer; | Specifies from which top/left column/row the import/export happens |
Options.ExportCellFormats: Boolean; | When true, cell format (string, integer, date, float) is exported, otherwise all cells are exported as strings. |
Options.ExportCellMargings: Boolean; | When true, the margins of the cell are exported |
Options.ExportCellProperties: Boolean; | When true, cell properties such as color, font, alignment are exported |
Options.ExportCellSizes: Boolean; | When true, the size of the cells is exported |
Options.ExportFormulas: Boolean; | When true, the formula is exported, otherwise the formula result is exported |
Options.ExportHardBorders: Boolean; | When true, cell borders are exported as hard borders for the Excel sheet |
Options.ExportHiddenColumns: Boolean; | When true, hidden columns are also exported |
Options.ExportHTMLTags: Boolean; | When true, HTML tags are also exported, otherwise all HTML tags are stripped during export |
Options.ExportImages: Boolean; | When true, images in the grid are also exported |
Options.ExportOverwrite: Boolean; | Controls if existing files should be overwritten or not during export |
Options.ExportOverwriteMessage: Boolean; | Sets the message to show warning to overwrite existing files during export |
Options.ExportPrintOptions: Boolean; | When true, the print options are exported to the XLS file |
Options.ExportShowGridLines: Boolean; | When true, grid line setting as set in TAdvStringGrid is exported to the XLS sheet |
Options.ExportShowInExcel: Boolean; | When true, the exported file is automatically shown in the default installed spreadsheet after export. |
Options.ExportSummaryRowBelowDetail: Boolean; | When true, summary rows are shown below detail rows in the exported XLS sheet |
Options.ExportWordWrapped: Boolean; | When true, cells are exported as wordwrapped cells |
Options.ImportCellFormats: Boolean; | When true, cells are imported with formatting as applied in the XLS sheet |
Options.ImportCellProperties: Boolean; | When true, cell properties such as color, font, alignment are imported |
Options.ImportCellSizes: Boolean; | When true, the size of cells is imported |
Options.ImportClearCells: Boolean; | When true, it will clear all existing cells in the grid before the import is done |
Options.ImportFormulas: Boolean; | When true, the formula is imported, otherwise only a formula result is imported |
Options.ImportImages: Boolean; | When true, images from the XLS sheet are imported |
Options.ImportLockedCellsAsReadOnly: Boolean; | When true, cells that are locked in the XLS sheet will be imported as read-only cells |
Options.ImportPrintOptions: Boolean; | When true, print settings as defined in the XLS sheet will be imported as grid.PrintSettings |
Options.UseExcelStandardColorPalette: Boolean; | When true, colors will be mapped using the standard Excel color palette, otherwise a custom palette will be included in the XLS sheet. |
TimeFormat: string; | Sets the format of cells with a time. When no format is specified, the default system time format is applied. |
XlsStartCol, XlsStartRow: integer; | Sets the top/left cell from where the import/export should start |
Advanced topics on exporting & importing
To apply transformations on cell data for loading and saving it is easy to create a descendent class from TTMSFNCGrid and override the SaveCell and LoadCell methods. In these overridden methods a transformation such as encryption or decryption can be applied. The basic technique is:
TEncryptedGrid = class(TTMSFNCGrid)
protected
function SaveCell(ACol,ARow: Integer):string; override;
procedure LoadCell(ACol,ARow: Integer; Value: string); override;
end;
function TEncryptedGrid.SaveCell(ACol,ARow: Integer): string;
begin
Result := Encrypt(GridCells[ACol,ARow]);
end;
procedure TEncryptedGrid.LoadCell(ACol,ARow: Integer; Value: string);
begin
GridCells[ACol,ARow] := Decrypt(Value);
end;
Sorting
The grid supports 2 types of sorting: normal sorting and indexed sorting. In normal sorting mode, the grid sorts the data ascending or descending on a specified column. In indexed sorting multiple columns can be marked and sorted ascending or descending. In both modes, the sorted column is marked with a triangle that is displayed with a number in indexed mode. The sort column can be set programmatically or by clicking on a fixed column header cell.
By default sorting is disabled. Enabling sorting can be done by setting the mode:
or In normal mode, when clicking on a column, or setting grid.SortColumn := 3 an indicator appears that indicates a column is sorted in ascending order.Clicking the same column again, changes the order to descending.
Setting the sorting mode to gsmIndexed will show a yellow triangle with an index number instead of a blue rectangle.
By default, the grid will automatically guess the data format of a cell to determine the compare method to use. It will detect regular strings, numbers and dates. Additional control over the compare methods to use per column is available via the event OnSortFormat:
TTMSFNCGridSortFormatEvent = procedure(Sender: TObject; Col: Integer;
var SortFormat: TSortFormat; var APrefix, ASuffix: string) of object;
The TSortFormat type is:
ssAutomatic: try to automatically guess the column data type to control the compare method
ssAlphabetic: cells contain text, compare with case sensitivity
ssAlphabeticNoCase: cells contain text, compare without case sensitivity
ssNumeric: cells in column contain a number, sort based on numeric comparisons
ssDate: cells in column contain a date, sort based on date comparisons
ssHTML: cells in column contain HTML formatted text, compare cells based on text without HTML tags
ssCheckBox: cells in column contain checkboxes, using compare of boolean values
ssCustom: a custom compare will be performed via the event OnCustomCompare
ssRaw: a custom compare will be performed via the event OnRawCompare.
The parameters APrefix, ASuffix allow to set a text as either prefix or suffix that will be ignored in the comparison. If the cell text is for example displaying a currency symbol like: 125.00$, by setting ASuffix to ‘$’, the comparison can be based just on the numeric data 125.00.
Custom sorts
Two events, OnCustomCompare and OnRawCompare are used to allow implementing custom compare routines when the sort format style is specified as ssCustom or ssRaw.
The OnCustomCompare is triggered for each compare of two string values and expects the result to be set through the Res parameter with values:
The OnRawCompare event is defined as:
It allows comparing grid cells [ACol,ARow1] and [ACol,ARow2] in any custom way and returning the result in the Res parameter in the same way as for the OnCustomCompare event.Example: comparing cell objects instead of cell text with OnRawCompare
As for each cell, an object can be assigned with the grid.Objects[Col,Row]: TObject property, it is easy to associate a number with each cell through:
Grid.Cells[Col,Row] := „I am text‟; // cell text
Grid.Objects[Col,Row] := TObject(1234); // associated number
procedure TTMSFNCGridOnRawCompare(Sender: TObject; ACol, Row1, Row2:
Integer; var Res: Integer);
var
c1,c2: Integer;
begin
c1 := integer(TMSFNCGrid1.Objects[ACol,Row1]);
c2 := integer(TMSFNCGrid1.Objects[ACol,Row2]);
if (c1 = c2) then
Res := 0
else
if (c1 > c2) then
Res := 1
else
Res := -1;
end;
Finally, two events that can be useful for sorting are: OnCanSortColumn and OnCellSortClick. The event OnCanSortColumn is triggered when a fixed column header cell is clicked just before an actual sort is performed. The event informs about the column clicked and passes the parameter Allow. By setting it to false, no actual sort is performed. The event OnCellSortClick is triggered after the sort on a specific column is done. While sorts in average sized grids is mostly instantanous, note that these two events could be used to set for example the mouse cursor as wait cursor from the OnCanSortColumn event and reset it to default cursor from the OnCellSortClick event when sorting very large grids.
To perform indexed sorting programmatically, add the columns that will be used as sort criteria to the grid.SortIndexes list. The first added column to the list is the first sort criteria, the second column added is the second criteria etc. For each sort column added, the sort order can be set with the second parameter of the AddIndex method. Call grid.SortIndexed after filling the SortIndexes list to perform the sorting.
TMSFNCGrid1.SortIndexes.Clear;
TMSFNCGrid1.SortIndexes.AddIndex(3, sdAscending);
TMSFNCGrid1.SortIndexes.AddIndex(4, sdDescending);
TMSFNCGrid1.SortIndexed;
To perform sorting on a single column click on the fixed column header of choice.To perform indexed sorting from the UI, click the first fixed column header cell to set the primary sort
column and after this, hold shift and click on the additional columns a sort criteria needs to be set for. A regular click removes all the indexes and sets the primary sort column again.
Note that when the grid is grouped, the sorting is automatically performed within groups. Sorting within groups can be based on a single column or can use indexed sorting as well. If it is needed that groups itself are resorted, perform an ungroup, perform the sort wanted and then regroup. To programmatically perform a sort in a grouped grid, call TMSFNCGrid.SortGrouped(Column, Direction). To programmatically perform an indexed sort in a grouped grid, add the indexes of columns to sort on first to the SortIndexes collection and then call TMSFNCGrid.SortGroupedIndex;
TMSFNCGrid1.SortIndexes.Clear;
TMSFNCGrid1.SortIndexes.AddIndex(5, sdDescending);
TMSFNCGrid1.SortIndexes.AddIndex(2, sdAscending);
TMSFNCGrid1.SortGroupedIndexed;
Grouping
TTMSFNCGrid has built-in single level automatic grouping and grouped sorting. This makes it easy to add grouping features with a few lines of code. Grouping means that identical cells within the same column are removed and shown as a grouping row for the other cells in the rows.
Example:
United States New York 205000 United States Chicago 121200 United States Detroit 250011 Germany Köln 420532 Germany Frankfurt 122557 Germany Berlin 63352
Grouped on the first column this becomes:
- United states New York 205000
Chicago 121200 Detroit 250011 - Germany Köln 420532 Frankfurt 122557 Berlin 63352
Grouped sorting on the first column becomes:
- United states Chicago 121200 Detroit 250011 New York 205000
- Germany Berlin 63352 Frankfurt 122557 Köln 420532
This is an overview of the grouping methods:
The Group method groups based on the column ColIndex. It automatically adds the expand / contract nodes. When expand / contract nodes are available, the normal sort when a column header is clicked changes to inter group sorting. Note that the column for grouping can only start from column 1, since column 0 is the placeholder for the expand / contract nodes.
To undo the effect of grouping, the UnGroup method can be used.
Example: loading a CSV file, applying grouping and performing a grouped sort
// loading CSV file in normal cells
TMSFNCGrid1.LoadFromCSV('cars.csv');
TMSFNCGrid1.ColWidths[0] := 20;
// do grouping on column 1
TMSFNCGrid1.Group(1);
// apply grouped sorting on (new) column 1
TMSFNCGrid1.SortGrouped(1, sdAscending);
Extra grouping features
Some extra capabilities for more visually appealing grouping can be set through the property grid.Options.Grouping. Through this property it can be enabled that group headers are automatically set in a different color and that cells from a group header are automatically merged. In addition, a group can also have a summary line. A summary line is an extra row below items that belong to the same group. This summary line can be used to put calculated group values in. The color for this summary line can also be automatically set as well as cell merging performed on this. See the grid.Options.Grouping description for all details.
Group calculations
TTMSFNCGrid has built-in function to automatically calculate group sums, average, min, max, count. The group results are set in the group header row if no summary row is shown, otherwise the group summary row is used by default. Group calculations are performed per column.
Available functions:
Function name | Description |
---|---|
grid.GroupSum(AColumn: Integer); | Calculates column sums per group |
grid.GroupAvg(AColumn: Integer); | Calculates column averages per group |
grid.GroupMin(AColumn: Integer); | Calculates column minimum per group |
grid.GroupMax(AColumn: Integer); | Calculates column minimum per group |
grid.GroupCount(AColumn: Integer); | Calculates number of rows in a group for each group |
grid.GroupDistinct(AColumn: Integer); | Calculates number of distinct rows in a group for each group |
grid.GroupStdDev(AColumn: Integer); | Calculates standard deviation of values in column AColumn within a group for each group |
grid.GroupCustomCalc(AColumn: Integer); | Allows to perform a custom calculation of group data with the event OnGroupCalc |
If there is a need for a special group calculation that is not available in the standard group calculation functions, the method grid.GroupCustomCalc can be used. For each group in the grid, this will trigger the event
The meaning of the parameters is: ACol : column to perform calculation for FromRow: first row in the group ToRow: last row in the group Res: variable parameter to use to set the result In this sample, the grid is initialized with random number, is grouped on column 1 and for the first column in the grouped grid the standard deviation is calculated:
procedure TForm1.TMSFNCGrid1GroupCalc(Sender: TObject; ACol, FromRow,
ToRow: Integer; var Res: Double);
var
i: integer; d, m, sd: double;
begin
// calculate mean
m := 0;
for i := FromRow to ToRow do
begin
m := m + TMSFNCGrid1.Floats[ACol,i];
end;
m := m / (ToRow - FromRow + 1);
// calculate standard deviation
sd := 0;
for i := FromRow to ToRow do
begin
sd := sd + sqr(TMSFNCGrid1.Floats[ACol,i] - m);
end;
sd := sd / (ToRow - FromRow);
Res := sqrt(sd);
end;
Column persistence
The grid offers various helper functions to deal in code with moving columns & sizing columns from the UI and persisting column width, column position and column visibility.
Following methods are available for this:
Methods name | Description |
---|---|
procedure SetColumnOrder; | It is important to note that all column movement tracking is done with respect to a reference column ordering. The reference column ordering is assumed to be the order of the columns when grid.SetColumnOrder is called. This internally initializes the sequence of the columns as the first column being column 0, the 2nd column being column 1, etc… All further column moving will be tracked against this ordering. As such, call grid.SetColumnOrder when the grid is initialized with data and the required grid.ColumnCount is set. |
procedure ResetColumnOrder; | Calling grid.ResetColumnOrder moves the columns back to the initial sequence, i.e. the sequence when grid.SetColumnOrder was called. Irrespective of how the user moved columns via column drag & drop, it will reset the grid to the original column sequence. This will not affect the column widths. |
function ColumnStatesToString: string; | This returns the states of each column as a string. This string can be easily stored in a registry or INI file or database for example. This string represents the current column ordering, the widths of the columns and the column visibility. The states of the columns returned via ColumnStatesToString is the state relative to the reference order determined at the time grid.SetColumnOrder was called. As such, a typical scenario is to call grid.ColumnStatesToString before the application closes and store this. With this stored value, the sequence and width of the columns can be restored to the state when the user left the application when it is restarted. |
procedure StringToColumnStates(States: string); | Assuming the grid is in reference column order (if not call grid.ResetColumnOrder), a previously stored state of columns can be restored by calling StringToColumnStates with the string that represents the state as parameter. |
function Columnposition(ACol: integer): integer; | When the reference column order is set, the function ColumnPosition() can be used to get the position of a specific column after the user moved columns around with drag & drop. |
function ColumnAtPosition(APosition: integer): integer; | When the reference column order is set, the function ColumnAtPosition can be used to return the index of the column in its reference order that is at a specific position after a user moved the columns around. |
Columns
The Columns collection manages designtime and runtime grid cell layout, types and behaviour as well as cell interaction capabilities such as sorting and editing. This behaviour is default and is controlled with the public UseColumns property.
When using combinations of dynamically created checkboxes at runtime and checkbox columns at designtime with the columns collection the preference is given to the dynamically created checkboxes.
Below are the properties that can be used to configure a grid column. All properties that are related to appearance / layout of a cell are applied only to normal cells. Other cell types are configured dynamically through one of the events that can be used to modify the cell layout.
Property name | Description |
---|---|
BorderColor: TTMSFNCGraphicsColor | Border color of a column grid cell in normal state. |
BorderWidth: Single | Border width of a column grid cell in normal state. |
Color: TTMSFNCGraphicsColor | Color of a column grid cell in normal state. |
ColumnType: TTMSFNCGridColumnType: | dentifies the type of the column. A column can be configured to show checkbox, radiobutton, button or progressbar cell types. The ColumnType property has a default value which is a normal grid cell type. |
ComboItems: TStringList | Used in combination with the Editor property. The ComboItems property is a stringlist that is assigned to the CellComboBox internally used for editing, when the editor type is etComboBox or etComboEdit. |
Editor: TTMSFNCGridEditorType | The editor type used to define the inplace editor that is used for editing and is identical to the editor type retrieved through the OnGetCellEditorType. Used in combination with the ComboItems property in case of etComboBox or etComboEdit. |
Fixed: Boolean | Sets the complete column as a fixed column. The cell type will be modified to a fixed cell type and therefore all layout properties such as Color, BorderColor and FontColor are ignored. |
FontColor: TTMSFNCGraphicsColor | The color of the font of a column grid cell in normal state. |
Font: TFont | The font of a column grid cell in normal state |
HorzAlignment: TTMSFNCGraphicsTextAlign | The horizontal alignment of a column grid cell text in normal state. |
ID: String | A unique identifier for each column to make sure each column can be accessed with this unique identifier after a column has been swapped, inserted or deleted. |
ReadOnly: Boolean | Sets the complete column readonly. The cells for that column remain normal cell types but are not editable. |
SortFormat: TSortFormat | The sorting format type of the column when sorting is applied (“Sorting” chapter). The property values can be set to ssAutomatic which will automatically identify the content of the column cells, a specific value such as ssAlphabetic, ssAlphabeticNoCase, ssNumeric, ssDate, ssHTML, ssCheckBox, ssRaw (OnRawCompare) or ssCustom (OnCustomCompare). |
SortSuffix: string | A sorting suffix used for additional sorting customization. |
SortPrefix: string | A sorting prefix used for additional sorting customization |
Tag: integer | A second unique identifier that can be used in a similar way as the ID property. |
VertAlignment: TTMSFNCGraphicsTextAlign | The vertical alignment of a column grid cell text in normal state. |
WordWrap: Boolean | The wordwrap of a column grid cell text in normal state. |
Filtering
The TTMSFNCGrid also supports built-in filtering. Filtering can be done programmatically or via the user interface when enabling the dropdown button on a fixed column header cell. When the dropdown button is visible, the dropdown list is automatically filled with unique values from the column. When selecting an item from the dropdown list, the grid is filtered based on the value you have selected:
By default, when setting grid.Options.Filtering.DropDown = true, all normal column header cells get a dropdown button. With the OnNeedFilterDropDown, the dropdown button / filtering can be enabled / disabled per column. When a dropdown filter button is displayed, this dropdown list is automatically filled with the unique values in the column but the OnNeedFilterDropDownData event is triggered and this allows to alter the data that is displayed in the dropdown list.
procedure TForm1.TMSFNCGrid1NeedFilterDropDownData(Sender: TObject;
Col,
Row: Integer; AValues: TStrings);
begin
AValues.Add('Hello World !');
end;

When an item from the filter dropdown is selected, this triggers the OnFilterSelect event. This returns the column and the selected filter condition and also allows to dynamically change the condition.
As the filter dropdown is filled automatically with unique values of a column, it is by default not possible to undo a filter from the user-interface. With the help of the OnNeedFilterDropDownData and the OnFilterSelect event, an item can be added to the dropdown that will undo the filtering.
Add the (All) options to the dropdown:
procedure TForm1.TMSFNCGrid1NeedFilterDropDownData(Sender: TObject; Col,
Row: Integer; AValues: TStrings);
begin
AValues.Add('(All)');
end;
When the (All) option is selected, set the condition to accept all values:
procedure TForm1.TMSFNCGrid1FilterSelect(Sender: TObject; Col: Integer;
var Condition: string);
begin
if Condition = '(All)' then
begin
Condition := '*';
end;
end;
TMSFNCGrid.ApplyFilter;
To remove the filter again at a later time, call TMSFNCGrid.RemoveFilter;
The TTMSFNCGridFilterData type in the Filter collection has following properties:
Condition: string : holds the condition, this is a string value including the use of <,>,&,|, *, ? specifiers CaseSensitive: Boolean : defines whether the condition is case sensitive or not Data: TFilterCells: specifies on what data the filter condition is applied. By default this is the cell text (fcNormal) Prefix: string: part of the cell text that should be ignored (at start of the cell text) Suffix: string: part of the cell text that should be ignored (at end of the cell text) Operation: TFilterOperation :defines the logical operation between the filter condition and the previous filter condition.
The definition of TFilterOperation is:
foSHORT: short circuit Boolean evaluation
foNONE: no logical operation (typical for first filter condition)
foAND: logical AND
foXOR: logical XOR
foOR: logical OR
When a column contains numbers formatted like:
The filter to get values larger than 60, could be :fd: TTMSFNCGridFilterData;
fd :=grid.Filter.Add;
fd.Column := 1;
fd.Suffix := ‘USD’
fd.Condition := ‘>50’;
To specify a filter that would retrieve values less than 30 or bigger than 60, this could be specified as:
fd: TTMSFNCGridFilterData;
fd :=grid.Filter.Add;
fd.Column := 1;
fd.Suffix := ‘USD’
fd.Condition := ‘>60’;
fd :=grid.Filter.Add;
fd.Column := 1;
fd.Suffix := ‘USD’
fd.Condition := ‘<30’;
fd.Operation := foOR;
HTML formatted text, cell anchors, highlighting and marking in cells
The grid supports HTML formatted strings in cells. This is based on a small & fast HTML rendering engine. This engine implements a subset of the HTML standard to display formatted text. It supports following tags :
B : Bold tag
Example : This is a test
U : Underline tag
Example : This is a testI : Italic tag
Example : This is a testS : Strikeout tag
Example : This is aA : anchor tag
<A href="value"> : text after tag is an anchor. The 'value' after the href identifier is the anchor. This can be an URL (with ftp,http,mailto,file identifier) or any text.
If the value is an URL, the shellexecute function is called, otherwise, the anchor value can be found in the OnAnchorClick event </A> : end of anchor
Examples : This is a test This is a test This is a test
FONT : font specifier tag
<FONT face='facevalue' size='sizevalue' color='colorvalue' bgcolor='colorvalue'> : specifies font of text after tag.with
Examples : This is a test This is a test
HR : horizontal line
<HR>
: inserts linebreak with horizontal line
BR : linebreak
<BR>
: inserts a linebreak
BODY : body color / background specifier
<BODY bgcolor="colorvalue" [bgcolorto="colorvalue"] [dir="v|h"] background="imagefile
specifier"> : sets the background color of the HTML text or the background bitmap file
Example :
<BODY bgcolor="gcYellow"> : sets background color to yellow
<BODY background="file://c:\test.bmp"> : sets tiled background to file test.bmp
<BODY bgcolor="gcYellow" bgcolorto="gcWhite" dir="v"> : sets a vertical gradient from yellow to white
IND : indent tag This is not part of the standard HTML tags but can be used to easily create multicolumn text
Example : This will beIMG : image tag
<IMG src="specifier:name" [align="specifier"] [width="width"] [height="height"]
[alt="specifier:name"] > : inserts an image at the location
specifier can be: name of image in a BitmapContainer
Optionally, an alignment tag can be included. If no alignment is included, the text alignment with respect to the image is bottom. Other possibilities are: align="top" and align="middle"
The width & height to render the image can be specified as well. If the image is embedded in anchor tags, a different image can be displayed when the mouse is in the image area through the Alt attribute.
Examples :
This is an image <IMG src="name">
SUB : subscript tag
Example : This is 9/16 looks like 9/16SUP : superscript tag
UL : list tag
Example :- The database table is editable
- The database field is editable
<LI>List item 1
<LI>List item 2
<UL>
<LI> Sub list item A
<LI> Sub list item B
</UL>
<LI>List item 3
</UL>
LI : list item
<LI [type="specifier"] [color="color"] [name="imagename"]>
: new list item specifier can be
"square", "circle" or "image" bullet. Color sets the color of the square or circle bullet. Imagename
sets the PictureContainer image name for image to use as bullet
SHAD : text with shadow
Z : hidden textSpecial characters Following standard HTML special characters are supported : < : less than : < > : greater than : > & : & " : " : non breaking space ™ : trademark symbol € : euro symbol § : section symbol © : copyright symbol ¶ : paragraph symbol
When hyperlinks are specified in grid cells, these hyperlinks are displayed underlined and in blue color. When the hyperlink is clicked, the OnCellAnchorClick event is triggered. Via HTML formatting, the grid also offers highlighting or marking of text in grid cells. This can be used to indicate text that matches a search or to show errors. The following methods are available for marking & highlighting in cells: Examples:
TMSFNCGrid1.HighlightInCol(false,false,2,'156');
Available methods:
Methods name | Description |
---|---|
TMSFNCGrid.HighlightInCell(DoCase: Boolean; Col,Row: Integer; HiText: string); | Highlight the text HiText with or without case sensitivity in cell Col,Row. |
TMSFNCGrid.HighlightInCol(DoFixed,DoCase: Boolean; Col: Integer; HiText: string); | Highlight the text HiText with or without case sensitivity in all cells in column Col. |
TMSFNCGrid.HighlightInRow(DoFixed,DoCase: Boolean; Row: Integer; HiText: string); | Highlight the text HiText with or without case sensitivity in all cells in row Row. |
TMSFNCGrid.HighlightInGrid(DoFixed,DoCase: Boolean; HiText: string); | Highlight the text HiText with or without case sensitivity in all cells in the grid. |
TMSFNCGrid.UnHighlightInCell(Col,Row: Integer); | Remove the highlighting in cell Col,Row. |
TMSFNCGrid.UnHighlightInCol(DoFixed: Boolean; Col: Integer); | Remove the highlighting in column Col, with or without fixed cells included. |
TMSFNCGrid.UnHighlightInRow(DoFixed: Boolean; Row: Integer); | Remove the highlighting in row Row, with or without fixed cells included. |
TMSFNCGrid.UnHighlightInGrid(DoFixed: Boolean); | Remove the highlighting in normal cells or all cells. |
TMSFNCGrid.UnHighlightAll; | Remove the highlighting in all cells |
TMSFNCGrid.MarkInCell(DoCase: Boolean; Col,Row: Integer; HiText: string); | Mark the text HiText with or without case sensitivity in cell Col,Row. |
TMSFNCGrid.MarkInCol(DoFixed,DoCase: Boolean; Col: Integer; HiText: string); | Mark the text HiText with or without case sensitivity in all cells in column Col |
TMSFNCGrid.MarkInRow(DoFixed,DoCase: Boolean; Row: Integer; HiText: string); | Mark the text HiText with or without case sensitivity in all cells in row Row. |
TMSFNCGrid.MarkInGrid(DoFixed,DoCase: Boolean; HiText: string); | Mark the text HiText with or without case sensitivity in all cells in the grid. |
TMSFNCGrid.UnMarkInCell(Col,Row: Integer); | Remove the marking in cell Col,Row. |
TMSFNCGrid.UnMarkInCol(DoFixed: Boolean; Col: Integer); | Remove the marking in column Col, with or without fixed cells included. |
TMSFNCGrid.UnMarkInRow(DoFixed: Boolean; Row: Integer); | Remove the marking in row Row, with or without fixed cells included. |
TMSFNCGrid.UnMarkInGrid(DoFixed: Boolean); | Remove the marking in normal grid cells or all grid cells. |
TMSFNCGrid.UnMarkAll; | Remove the marking in all grid cells. |
Databinding
The TTMSFNCGrid supports databinding via the TTMSFNCGridDatabaseAdapter. This adapter is responsible for connecting to the dataset and for loading, displaying and editing the data. The adapter exposes a set of properties for data visualization and manipulation and a column collection that represents the available fields. Below is an overview of the available properties and events.
Property name | Description |
---|---|
Active | Activates the adapter and displays the data from the dataset when the dataset is active. |
AutoCreateColumns | When true, automatically retrieves the fields from the dataset and creates columns for each field. The columns in the grid match the columns in the dataset |
AutoRemoveColumns | When true, automatically removes all columns when the dataset deactivates or changes. |
Columns | A column collection which is automatically filled with data from the dataset when AutoCreateColumns is true. The column collection contains properties to change the visualization and manipulation of data for each column. The columns collection on adapter level is automatically synchronized with the columns on grid level and work together |
DataSetType | The type of dataset (sequential or non-sequential). Automatically preset when DataSetTypeAuto is set to true. The DataSetType property can be set manually when DataSetTypeAuto is set to false |
DataSetTypeAuto | When true, automatically determines the type of dataset (sequential or nonsequential) and presets the DataSetType property |
DataSource | The datasource, connected to the dataset. |
Grid | The grid, to display the data from the dataset. |
PostMode | The post mode when editing an existing or new record. By default, the PostMode is set to apmRow which means that the new information is posted when the row changes. The |
alternative is apmCell, which means that the new information is posted when the cell changes. To manually handle data posting, set the PostMode to apmNone. | |
ShowBooleanFields | When true, shows a checkbox and tries to convert the value to a Boolean when Boolean information is available. |
ShowMemoFields | When true, the grid will display the contents of the memo field instead of displaying a placeholder |
ShowPictureFields | When true, the grid will display the image from a blob field or graphic field. |
At column level, the following properties are available:
Property name | Description |
---|---|
CheckBoxField | When true, the field is treated as a Boolean field represented by a checkbox. |
CheckFalse | Sets the value of the DB field that corresponds with an unchecked checkbox. |
CheckTrue | Set sthe value of the DB field that corresponds with a checked checkbox. |
FieldName | Sets the fieldname for the dataset field that is displayed in the column. |
Header | Sets the column header text. When empty, the FieldName.DisplayLabel is used as a column header text. |
HTMLTemplate | Sets the HTML template of the column. This allows to display multiple DB fields in one column. |
PictureField | When true and a blob field is connected to the column, the blob data is treated as an image and displayed. |
ProgressField | When true, the field value in the column is treated as a value to set the progressbar. Note that this requires that the field value is between 0 and 100. If this is not available in the dataset, a calculated field could be used to generate a value between 0 and 100. |
UseColumnEditor | Specifies whether to use the editor defined at grid column level or the one automatically determined by the database adapter. |
UseLookupEditor | Specifies whether to use a lookup editor combobox for the column. |
Memo fields, Boolean fields & image blobs
The TTMSFNCGridDatabaseAdapter can automatically display memo fields, can show Boolean fields as checkboxes in the grid and can display images stored in blob fields. By default, a memo field is displayed as ‘(MEMO)’ and an image blob is displayed as ‘(GRAPHIC)’ just like in the default TGrid or TStringGrid in FMX, VCL and LCL. To show real contents of memo fields, set global property ShowMemoFields = true. To have the cell sizes automatically sized according to the text in memo fields, it is sufficient to call Grid.AutoSizeRows(false,4) after activating the dataset. By default, a DB field of the type ftBoolean is displayed as value ‘true’ or ‘false”.
The adapter can also automatically show such ftBoolean field type as a checkbox. To do this, set ShowBooleanFields = true. One step further is that the adapter can also show checkboxes for DB fields that do not have the type ftBoolean but that can have two values. This can be used with databases that do not support Boolean field types for example where a true condition is stored in a field as one value and false condition is stored as another value. To show checkboxes for such fields, set Columns[columnindex].CheckBoxField = true and set via the properties Columns[columnindex].CheckTrue, DBAdvGrid.Columns[columnindex].CheckFalse the values for a true condition and false condition.
The adapter can also show BMP, GIF, JPEG images that are stored in BLOB fields. By default, such fields are displayed as ‘(GRAPHIC)’. When setting ShowPictureFields = true, all fields with the type ftGraphic will be displayed as images. In some databases, the field type for an image field will not be ftGraphic but just ftBlob for example. The grid cannot automatically know that the BLOB data should be interpreted as an image though. If a DB field of the type ftBlob holds images, Columns[columnindex].PictureField can be set to true and for this column, the grid will try to display the BLOB data as BMP, GIF or JPEG image.
HTML Templates
Through a HTML template, it is possible to put multiple fields in a single cell with optionally HTML formatting. This is done by specifying a HTML template via the property
Columns[Index].HTMLTemplate
. The HTML template is a string where a DB field reference set by <#DBFIELDNAME>
will be replaced by the DB field value for each record for display. For example, when a table has a field Length (cm), the following HTML template creates a single cell with text in blue & bold: Columns[2].HTMLTemplate := ‘<FONT color="gcBlue">Length is </FONT> <B><#Length (cm)> ft</B>’; The resulting grid looks like:
Editing
The adapter supports various inplace editors as well as the capability to use external controls as inplace editor for the grid. The “Editing” chapter in this document has an overview of all possible inplace editors that are included and how to use external editors as well. To enable editing in the grid, it is required that
The adapter can perform editing in two modes. This is selected by the property PostMode. When this is set to apmCell, the value that has been edited is posted immediately to the database when a cell leaves inplace editing. When PostMode is set to apmRow, a post operation will only occur when all cells in a row have been edited and the user moves to another row. Typically, for tables with various required fields, apmRow is the preferred setting.
When a selected cell is clicked, the inplace editing starts. It is important to know that editing of a cell or row stops when the inplace editor loses focus. Only when it loses focus, the edited value is either directly posted (apmCell mode) or internally stored (apmRow mode) to post when the row changes.