Classes for displaying tabular data in the form of a grid of rows and columns EGridException - exception handler for an error in a Grid class TStringCellEditor - the default editor for TStringGrid msg_SetMask - issues message for specifying mask msg_SetValue - issue message for specifying value msg_GetValue - issues message for obtaining value msg_SetGrid - issues message for specifying grid msg_SelectAll - issues message for Selecting All TVirtualGrid - an array of rows and columns containing data, which never gets displayed doDestroyItem - method for destroying an Item at the given Row and Column location doNewItem - method for producing a new item at the given location specified by Row, Col DeleteColRow - remove either a column or a row, depending on the value of IsColumn MoveColRow - move either a column or a row (depending on value of IsColumn) at FromIndex to the location ToIndex ExchangeColRow - exchange either the current column or row (depending on the value of IsColumn) with the entity specified by WithIndex DisposeCell - dispose of the resources and pointer for the given cell DisposeColRow - dispose of the specified row or column, freeing its pointer Create - constructor for TVirtualGrid: calls inherited Create then creates arrays of Cells, Columns and Rows; forms links for actions and event handlers TObject.Create Destroy - destructor for TVirtualGrid: frees rows, columns and cells, then cals inherited Destroy TObject.Destroy Clear the grid GetDefaultCell - returns the properties of the default cell GetDefaultColRow - returns the properties of the default column and row ColCount - the number of columns in the current grid RowCount - the number of rows in the current grid Celda - the current cell as defined by its column and row Cols - the columns to which the grid applies The Rows to which the grid applies TCustomGrid - the base class for all grid controls

A grid is a collection of cells that are organized in columns and rows. Grids are suitable for showing data that have tabular nature, for example tables in a database, or formulae and data in a spreadsheet.

Key properties:

The ColCount and RowCount properties contain the column and row count of the grid.

The FixedCols and FixedRows properties specify the count of fixed columns or rows that are used for headings.

The column widths and row heights of the grid are accessible with the ColWidths and RowHeights properties.

The DefaultColWidth and DefaultRowHeight properties are used to specify default column widths or row heights respectively.

The colors of the cells and the grid elements are specified with the AlternateColor, BorderColor, FixedColor, FixedHotColor, FocusColor, GridLineColor and SelectedColor properties. The GridWidth and GridHeight properties contain the dimension of the entire grid.

The ScrollBars property controls the creation of scrollbars for the grid.

The LeftCol, TopRow, VisibleColCount and VisibleRowCount properties contain information about the visible area of the grid.

The Options property controls options for the grid.

Key methods and events:

If the user highlights a cell of the grid, the SelectCell method is called that triggers the OnSelectCell event. The position of the highlighted cell is stored within the Col and Row property.

The MouseToCell method calculates a grid cell from a given screen position.

Huge changes to the grid should be encapsulated in calls to BeginUpdate and EndUpdate to speed up the application.

Component developers must override the DrawCell method in customized grids.

EditorHide - method for hiding the editor EditorSelectAll - editor procedure to Select All EditorShow - shows the cell contents in the Editor Read specifier for LeftCol Read specifier for ColWidths Read specifier for RowHeights Returns the current rowheight Read specifier for TopRow Read specifier for VisibleRowCount Write specifier for Col Write specifier for RawColWidths Write specifier for ColCount Write specifier for DefColWidth Write specifier for DefRowHeight Write specifier for Editor Write specifier for FixedCols Write specifier for FixedRows Write specifier for GridLineColor Write specifier for LeftCol Write specifier for Options Write specifier for Row Write specifier for RowCount Write specifier for ScrollBars Write specifier for TopRow UpdateSelectionRange - updates the range of the current selection fGridState - local variable to hold current state of the grid (whether being edited, updated etc) AutoAdjustColumn - automatically adjust column properties to accommodate largest object BeforeMoveSelection - method to use before a selection is moved This method is called from TCustomGrid.MoveExtend method whenever the current grid cursor location is about to change. The destination column and row are specified in DCol and DRow parameters respectively. The new location is known to be a valid selectable cell (see ), and is given in absolute cell coordinates. At this point the current grid location has not changed and can be retrieved with Col and Row properties. The purpose of this method is to call event handler OnBeforeSelection. CalcAutoSizeColumn - method for automatically calculating the size of a column CalcFocusRect - method for calculating the bounds of a focused rectangle CellClick - method for processing a click in a cell CheckLimits - method for checking limits of specified cell ColRowDeleted - method for dealing with deletion of either a column or a row (depending on value of IsCol) ColRowExchanged - method for exchanging the current Column or Row (depending on value of IsCol) with the indexed other column or row ColRowMoved - the column or row (determined by IsColumn) is moved from one index to another ColRowToOffset - method for moving column or row (depending on value of IsCol); if Relative is True, moves by the amount of Index, otherwise moves from StartPos to EndPos. Returns True if successful ColWidthsChanged - method for dealing with changes in column width DrawBorder - draws the border of the grid DrawCell - draws a cell at the given grid location (Col, Row) or in the specified Rectangle DrawCellGrid draws a grid of cells at the specified location DrawColRowMoving - draw a column or row while it is moving DrawEdges of the current grid DrawFocusRect - draw a rectangle with focus in the nominated cell DrawRow - draws the specified row EditordoGetValue - method for geting a value in the Editor EditordoSetValue - method for specifying a value in the Editor EditorCanAcceptKey - returns True if the Editor is able to accept the nominated (UTF8) key EditorIsReadOnly - returns True if the Editor has Read Only status GetAutoFillColumnInfo - finds out information (max, min, priority) about the auto-fill properties of the indexed column GetFixedcolor - returns a value for the fixed colour GetSelectedColor - returns the value for the colour of tems that have been selected GetEditMask - returns the edit mask string for the specified cell GetEditText - returns the Edit text string for the specified cell SetEditText - specifies the text-string to be placed in the Editor for processing HeaderClick - method to deal with a click on the column (if IsColumn is True) or row Header HeaderSized - method to deal with re-sizing of a column (IsColumn True) or row header InvalidateCell - render a cell non-valid, and redraw if required InvalidateCell - render a cell non-valid, and redraw if required InvalidateCol - render the specified column non-valid InvalidateGrid - render the whole grid non-valid InvalidateRow - render the specified row non-valid LoadContent - method to load a configuration MoveExtend - move an extended selection; if Relative is true, use Delta column and row to find position; returns True if successful MoveNextAuto - move to next cell in automatic sequence; if Relative is True, use delta col and row to find position; returns True if successful MoveNextSelectable - move to next selectable cel; use delta col and row if Relative is True; returns True if successful MoveSelection - moves the selected text, cell or group of cells OffsetToColRow - move by the value of Offset to another column or row (determined by the value of IsCol), returning True if successful PrepareCanvas - method to get the canvas ready for drawing at the specified location ResetOffset - resets the offset, checking columns and rows if demanded RowHeightsChanged - method invoked when row heights are changes SaveContent as specified in the XML configuration variable ScrollBarRange - specify the range of the scrollbar; Which determines whether it is horizontal or vertical ScrollBarPosition - records the position ( Value) of the scrollbar; Which determines horizontal or vertical ScrollBarPage - a Page movement of the scrollbar (specified by Which) ScrollBarShow method Change the appearance of the scrollbars in the grid. 'Which' can be any of : SB_BOTH, SB_VERT, SB_HORZ 'aValue' can be True or False ScrollBarAutomatic method Check if scrollbars are shown automatically by the grid or not. 'Which' can be any of : SB_BOTH, SB_VERT, SB_HORZ SelectEditor - chooses the editor for current use Is called if a grid cell is highlighted.

The SelectCell method is called if a grid cell will be highlighted.

The aCol and aRow parameters contain the column and the row of the highlighted cell.

Component developers may use the SelectCell method to react on focus changes. The Result is true if the cell is allowed to be selected. Application developers should use the OnSelectCell event instead.

SetBorderStyle - specifies a new border style SetFixedcolor - specifies colour for fixed cells SetSelectedColor - specifies colour for cells that have been selected SizeChanged - specifies the old number of columns and rows Sort method

Method to sort all items in the grid

If ColSorting is True, sorts the items in a column; otherwise sorts a row

The three given indexes specify the items to be sorted

TopLeftChanged - the top left cell has changed TryMoveSelection - attempts to move the selection by the specified offset; returns True if sucessful UpdateHorzScrollBar - updates the scrollbar in the given range by the given page, if it is visible UpdateVertScrollbar - updates the scrollbar in the given range by the given page, if it is visible VisualChange - a change in the visual properties WMHScroll - system message for horizontal scrolling WMVScroll - system message for vertical scrolling Automatically advance down the grid on successive mouse clicks or presses of the ENTER or TAB key Automatically resize columns so they fill all grid's visible area

When this option is turned on, the grid will resize all columns to fill the grid's client width. What columns are resized is determined by the following conditions:

1. Fixed Columns are not resized. 2. If the grid has Custom Columns, all columns with SizePriority=0 are not resized.

Note that Custom Columns are initially created with SizePriority=1. For TDbGrid, which automatically adds Custom Columns, this means the user will not be able to resize such columns using the mouse.

Only a restricted series of options is available: none or a single border. Current column index. Col property holds the column index of the current grid cell cursor. The current grid column can be changed programatically by setting a new value to this property. Number of columns of the grid. This is the number of columns in the grid, including fixed and normal columns. Column widths for the grid.

The column is specified with the aCol parameter. The aCol parameter must fall within the valid index range of 0 to ColCount-1.

The return value of the property is the width of this column, measured in pixels.

The initial width of a newly created column is specified with the DefaultColWidth property. After that the user may redefine this value.

If the Options property includes the appropriate value, the column width may also be changed by the user at runtime.

Default value for the width of newly created grid columns.

If new columns of the grid are created by changing the ColCount property, the width of these new columns will be set to the value of the DefaultColWidth property.

After that the user may redefine this value. If the Options property includes the appropriate value, the column width may also be changed by the user at runtime.

Default value for the height of newly created grid rows.

If new rows of the grid are created by changing the RowCount property, the height of these new rows will be set to the value of the DefaultRowHeight property.

After that the user may redefine this value. If the Options property includes the appropriate value, the row height may also be changed by the user at runtime.

Is the default drawing method to be used for this grid? Default is TRUE Default style for displaying text - includes alignment, layout, single or multi-lines DragDx - the amount (DeltaX) by which an object should be dragged The editor to be used for modifying information in the cells of the grid Is grid ready to accept edits? (EditorMode True) EditorKey - is the current key available to the editor? Is the editor for the grid displayed? Number of the fixed columns of the grid (ie the columns containing title or identifier material, that don't get scrolled when the rest of the grid moves).

Contains the fixed column count of a grid.

Fixed columns are normally used for headings.

Number of the fixed rows of the grid (ie the rows containing title or identifier material, that don't get scrolled when the rest of the grid moves).

Contains the fixed row count of a grid.

Fixed rows are normally used for headings.

The color for the fixed cells of the grid. The color used by headings. Is the cell to be displayed Flat, ie with no texturing or raised/lowered effect The colour to be used for the cell receiving focus FocusRectVisible - is the rectangle receiving focus visible? GCache - the cache to be used for grid data GridHeight - the height of the grid Colour to be used for GridLines Style to be used for GridLines Width (thickness) of GridLines Width of the whole Grid LeftCol - the left-most column The options available for use in this grid For a list of options see The current Row (record) within the grid Number of rows in the grid This is the number of rows in the grid, including fixed and normal rows. The row heights for the grid.

The row is specified with the aRow parameter. The aRow parameter must fall within the valid index range of 0 to RowCount-1.

The return value of the property is the height of this row, measured in pixels.

The initial height of a newly created row is specified with the DefaultRowHeight property. After that the user may redefine this value. If the Options property includes the appropriate value, the row height may also be changed by the user at runtime.

The set of options for saving information from the grid (design, attributes, content or position) These options are used when saving grid information, but also when loading grid information. SelectActive - if True, the current active cell is selected Colour to be used for selected cells The current selection (rows and columns) in the grid The ScrollBars to be used with this grid The first row (record) in the grid The number of visible columns The number of visible rows OnBeforeSelection - event handler for use before a selection is made Event handler for comparing the contents of grid cells Event handler to prepare the Canvas for drawing Event handler for drawing a cell Event handler for when an area of a grid (one or a group of cells) is selected The Col and Row parameters contain the column and the row of the highlighted cell. Application developers may use the OnSelection and OnBeforeSelection events to react on focus changes. Component developers should use the method instead. Event handler for selecting an editor Event handler when the top left cell is changed (ie the grid has been scrolled so that a different cell occupies top left) Create - constructor for TCustomGrid: calls inherited Create, then creates lists of columns and rows, initialises many visual properties and options, creates the various editors and loads any bitmaps required for the display

// Inherited create Calls SetBounds->WM_SIZE->VisualChange so

// fGrid needs to be created before that

TCustomControl.Create
Destroy - destructor for TCustomGrid: frees various resources including editors, columns, rows, font then calls inherited Destroy TCustomControl.Destroy AutoAdjustColumns - automatically adjust the columns according to the size of their contents Begin updating the grid The coordinates of the current cell (column, row) expressed as a standard rectangle (TRect) Clear all cells from the grid.

Reset Column and Row counts to 0. Grid is completely emptied.

Compatibility: This property applies to Lazarus grids only , under Delphi/Kylix a grid can't be completely emptied.

Leave the cell editor Emulate the OnKeyDown event handler in the cell editor Emulate the OnKeyPress event handler in the cell editor Emulate the OnKeyUp event handler in the cell editor EndUpdate - Finish updating the grid EndUpdate - Finish updating the grid IsCellSelected - is the cell specified by aCol, aRow selected? Finds out whether a particular cell is visible Load the grid data from a file with the specified name Note that the SaveOptions property determines what information is loaded. Convert mouse coordinates to the position of a cell in the grid Convert mouse coordinates to the position of a cell in the grid Convert mouse coordinates to the position of a logical cell in the grid MouseToGridZone - convert muse coordinates to a gid zone Save the data in the grid to a file with specified name Note that the property SaveOptions determines what information is saved. TDrawGrid - a drawn grid. May contain images in its cells TStringGrid - a specialised grid for displaying strings (text material) in a matrix of columns and rows Draw rubberband rect Draw a rubberband around the provided cellrect Segunda linea de texto TGridColumn - a column of similar data items in a grid TButtonCellEditor - the editor for button cells in a grid msg_SetGrid - issues message for specifying grid msg_SetPos - issues message for specifying position Col - the column in which the edited cell resides Row - the row in which the edited cell resides TPickListCellEditor - the editor for a picklist cell in a grid msg_GetValue - issues a message to find the value msg_SetGrid - issues a message to specify the grid msg_SetValue - issues a message to specify the value InsertColRow - insert either a column or a row (depending on value of IsColumn) at the specified index position TGridColumnTitle - the title for a column in a grid

TGridColumnTitle - the title for a column in a grid

The actual title is held in Caption

Column refers to the Grid Column to which the Title is attached

GetDefaultCaption - returns th e default caption for this column GetDefaultAlignment - returns the default alignment GetDefaultColor - returns the default colour GetDefaultLayout - returns the default layout SetCaption - specifies the caption to use (rather than using default) Create - constructor for TGridColumnTitle: calls inherited Create then links the column, creates and configures the default font TObject.Create Destroy - destructor for TGridColumnTitle: frees forn, disconnects alignments, disposes of captions and colours then calls inherited Destroy TPersistent.Destroy FillTitleDefaultFont - use the default font for the whole of the title IsDefault - returns True if this is the default title The Column to which the title applies The Alignment (whether justified or centred) for this title The Layout for the text of the title The Caption for this title The Color to use for this title The Font for this title GetPickList - returns the picklist as a list of strings GetDefaultAlignment - returns the default alignment GetDefaultColor - returns the default colour GetDefaultLayout - returns the default layout for text GetDefaultMaxSize -returns the default maximum size GetDefaultMinSize - returns the default minimum size GetDefaultReadOnly - returns the default value for the ReadOnly property GetDefaultSizePriority - returns the default value for size priority GetDefaultVisible - returns the default value for the Visible property GetDefaultWidth - returns the default value for width ColumnChanged - method for dealing with change of column AllColumnsChange - method for processing a change in all columns CreateTitle - creates a column title and returns it in the result IsDefaultFont - if True, the default font is being used Create - constructor for TGridColumn: calls inherited Create, then creates a title and font, initialises a picklist and sets styles TCollectionItem.Create Destroy - destructor for TGridColumn: disposes of various local variables, frees picklist, font and title, then calls inherited Destroy TCollectionItem.Destroy FillDefaultFont - method to fill all cells in the column with the default font IsDefault - returns True if this column is the default The Grid to which this column belongs WidthChanged - if True, width has been changed Alignment - whether justified, centred etc ButtonStyle - the style of any column button the Color for this column DropDownRows - the number of rows in the drop-down list Whether the column has been Expanded The Font for the column The Layout for text MinSize - the minimum size MaxSize - the maximum size PickList - the list of items selected from this column ReadOnly - if True, only reading (not writing) is allowed SizePriority - the value of the size priority in the sorted order The Title for the column The Width of the column Visible - if True, the column can be seen (ie not hidden) TGridColumns - the group of columns in the grid TitleFontChanged - method to deal with a change in title font FontChanged - method to deal with a change in font for the columns RemoveColumn - method to remove the specified column MoveColumn from the first index to the second ExchangeColumn - exchange the position of the current column with the specified other column InsertColumn with the specified index Create - constructor for TGridColumns: calls inherited Create then loads the grid TCollection.Create RealIndex - the proper index for this column Real in this sense means proper or correct, not a Real number (as it is specified as an integer) IndexOf this column IsDefault returns True if this is the default column HasIndex - returns True if the current column has an index value VisibleIndex - the index value of a visible column The Grid to which the current collection of columns belongs Items - the list of columns in this collection VisibleCount - the number of visible columns If True, the columns are Enabled CanEditShow - returns True if the editing data can be shown CanGridAcceptKey - returns True is the grid is able to accept the given key CheckLimitsWithError - method for checking limits of specified cel, with error trapping CMMouseLeave - Control Message for a mouse leaving a cell ColRowInserted - method for dealing with insertion of a column or row (depending on value of IsCol) ColumnIndexFromGridColumn - extracts the index of the specified grid column ColumnFromGridColumn - returns the actual grid column given its index ColumnsChanged - method for dealing with changed columns CreateColumns - returns the identity of the created columns CheckNewCachedSizes - check the new values of cached sizes DoCompareCells - perform the comparison of two or more cells in a grid DoCopyToClipboard - copy the selected data to the clipboard, leaving the original data in place DoCutToClipboard - cut the data from its current site and place it on the clipboard DoEditorHide - hide the data in the editor DoEditorShow - show the data in the editor DoOPDeleteColRow performs the operation for deleting a column or row (depending on value of IsCol) DoOPExchangeColRow - perform the operation for exchanging either the current column or row (depending on value of IsCol) with the column or row specified by WithIndex DoOPInsertColRow - perform th eoperation for inserting either a column or a row (depending on the value of IsCol) at th indexed position DoOPMoveColRow - performs the operation for moving either a column or a row (depending on the value of IsCol) between FromIndex and ToIndex DoPasteFromClipboard paste the data from the clipboard to the current location DoPrepareCanvas - get the canvas ready for drawing DrawAllRows - draws all the rows DrawCellText - draws the given text string in the cell specified by Col, Row or by Rectangle DrawColumnText - draw the text of the specified column EditButtonClicked - calls OnEditButtonClick EditorLocked - returns True if the Editor is locked, ie unable to accept input or make changes EditorShowInCell - shows the Editor's content in situ in the Cell EditorWidthChanged - method for dealing with a change in editor width FixedGrid - returns True if the Grid is fixed FontChanged - method to deal with a change in font GetColumnAlignment - returns the Alignment value for the nominated column GetColumnColor - returns the Colour for the specified column GetColumnFont - returns the font for the specified column GetColumnLayout - returns the Text Layout value for the specified column GetColumnReadonly - returns True if the column is marked ReadOnly GetColumnTitle - returns the column title string GetColumnWidth - returns the width of the column GetDeltaMoveNext return the relative cell coordinate of the next cell to which movement will occur GetDefaultColumnAlignment - returns the default alignment for the specified column GetDefaultColumnWidth - returns the default width for the specified column GetDefaultColumnLayout - returns the default text layout for the nominated column GetDefaultColumnReadOnly - returns the default setting of the ReadOnly flag for the specified column GetDefaultColumnTitle - returns the default title string for the specified column GetDefaultEditor - returns the default editor for the specified column GetDefaultRowHeight - returns the default row height GetScrollBarPosition - returns the position of the scroll bar specified by Which GetSBVisibility - finds the values of the visibility flags for the scrollbars GetSBRanges - finds the ranges of values for the scrollbars, if they are visible GridColumnFromColumnIndex - returns the number of the column given its column index InternalSetColCount - specify the column count InvalidateRange - render a range of the grid non-valid InvalidateFromCol - render the grid non-valid from the specified column onwards InvalidateFocused - render the focused item non-valid GetIsCellSelected - returns True if the given cell is selected LockEditor - lock the editor so that it will not accept input or changes PickListItemSelected - indicates that an item was selected from the pick-list ResetEditor - resets the current editor for the grid ResetSizes - resets the sizes ResizeColumn - resizes the nominated column to the specified width ResizeRow - resizes the nominated row to the specified height ScrollBarIsVisible - Returns True if visible; Which determines whether horizontal or vertical SetCanvasFont to specified value SetColor to specified value SetColRow - specifies the column and row for addressing UnLockEditor - frees a previously locked Editor UpdateBorderStyle - brings the border style up to date AllowOutboundEvents - permits mouse click on an imaginary (out-of-bounds) cell; moves cursor to nearest valid cell

Normally when a user clicks on a point over the empty space after cells (for example if grid has three rows but user clicks on imaginary fourth row) the current focused cell will move to the nearest cell to clicked point; we call this an outbound event.

Default value is true, as this has been the grid's behaviour since the beginning.

This property was added to simulate Delphi behaviour where outbound events are not available; to enable Delphi compatibility set this property to false.

The colour to be used for the background on alternate rows of the grid. Having alternate rows in different colours can make the grid easier to read. Whether the Edit mode is automatically entered when a cell is selected The colour of the border for this control The properties of the columns in this grid

The Columns property of a grid refers to the physical column in the table, and determines its size, shape, colour etc. It should not be confused with the COLUMNS construct frequently used in SQL programming, which refers to Fields of data. The contents of Fields can be displayed as Columns in a Grid, but they must be seen as separate and distinct. It is irrelevant to refer to the colour, font or width of a data field from a database, but these are all very relevant in specifying the appearance of a column in a grid.

The border style for the editor used in this grid The set of options available for the grid's editor ExtendedColSizing - the sizing to be used for extended columns ExtendedRowSizing - the sizing to be used for extended rows ExtendedSelect - the ability to select cells beyond the boundary of the visible part of the grid Is the FastEditing method being used? AltColorStartNormal - using a second colour to display alternate rows, but starting the first row with the normal colour

AltColorStartNormal - using a second colour to display alternate rows, but starting the first row with the normal colour

Using a different colour for the background of alternate rows often makes the data in a grid much easier to read

FixedHotColor - the 'Hot' colour for the active (selected, etc) fixed cells of the grid GridFlags - the flags that are set for the grid HeaderHotZones - the zones of the header that are under the cursor, so are capable of being selected or pushed (or not!) HeaderPushZones - the zones of the header that have been selected by the cursor, or pushed InplaceEditor - the editor to be used in-place, ie in the cell itself instead of outside the grid The column (field) currently selected StrictSort - is strict sorting to be used? The font to be used in the grid's title The style to be used for the grid's title UseXORFeatures: When True, the dotted focus rectangle is painted using the XOR raster operation

This property controls how the dotted focus rectangle appears in the grid. When True, the rectangle is painted using the XOR raster operation. This allow us to see the focus rectangle no matter what the cells' background color is. When False, the user can control the color of the dotted focus rectangle using the FocusColor property

It also controls the look of the column/row resizing. When True, a line shows visually the size that the the column or row will have if the user ends the operation. When False, the column or row resizing takes effect just as the user drags the mouse

Event handler for when the Edit button is clicked Event handler for selecting an item from a picklist (eg drop-down list in TComboBox) Convert the coordinates of the current cell (col, row) to a grid zone Check the position of the cursor Select a cell editor control with the specified style Clear the background to the grid Find the mouse coordinates relative to the grid origin Set focus on the grid Order of sorting - ascending or descending TCustomDrawGrid - Base Class for drawn grids including TDrawGrid and TStringGrid FGrid - local variable holding a virtual grid on which to work CalcCellExtent - calculate the dimensions required for the cell specified by aCol, aRow CreateVirtualGrid - returns the created virtual grid DrawCellAutonumbering - draws a cell using auto numbering DrawFocusRect - draws the rectangle currently receiving focus NotifyColRowChange tells the system that a column or row has been changed (determined by IsColumn) and whether this was an Insert Create - constructor for TCustomDrawGrid: attaches a virtual grid then calls inherited Create TCustomGrid.Create Destroy - destructor for TCustomDrawGrid: frees the grid then calls inherited Destroy TCustomGrid.Destroy Delete either a column or a row (specified by index), depending on the value of the boolean IsColumn Exchange either a column or a row, specified by index, with the col or row specified by WithIndex; boolean IsColumn determines whether rows or columns are to be exchanged InsertColRow inserts a column or row (specified by Iscolumn) at the stated index location Move column or row from FromIndex to ToIndex; boolean IsColumn specifies whether col or row is to be moved Sort column or row specified by index and optionally by FromIndex and ToIndex; IsColumn specifies whether col or row is to be sorted Use the default method for drawing a cell specified by aCol, aRow, at location aRect with state aState Event handler when a grid column or row is deleted Event handler when a grid column or row has its position exchanged with another Event handler when a column or row is inserted into the grid Event handler when a grid column or row is moved Event handler for comparing the contents of cells Event handler for finding the edit mask while editing a grid cell Event handler for finding the text to be edited in a grid cell Event handler when a column or row header is clicked Event handler when a column or row header is re-sized Event handler when a grid cell is selected Event handler for storing the text that has been edited in a cell HeaderHotZones - the header zones corresponding to the position of the mouse cursor HeaderPushZones - the zones of the header that have been pushed down (selected) TCustomStringGrid - base class for TStringGrid TStringGridStrings - the strings that populate the cells of a TStringGrid All of the properties are defined in the ancestor classes (TStrings etc) Create - constructor for TStringGridStrings: calls inherited Create and initialises some local variables TObject.Create SelectionSetText - stores the text in the selection Whether or not the current cell has been Modified Create - constructor for TCustomStringGrid: calls inherited Create then sets up default styles, layout and alignment TCustomDrawGrid.Create Destroy - destructor for TCustomStringGrid: frees maps of columns and rows, then calls inherited Destroy TCustomDrawGrid.Destroy AutoSizeColumn - automatically adjust width of column to accommodate widest text

This procedure sets the column width to the size of the widest text it finds in all rows for the column aCol.

Tip: see the goDblClickAutoSize option to allow columns to be automatically resized when doubleClicking the column border.

AutoSizeColumns - automatically resizes all columns by adjusting them to fit in the longest text in each column Automatically resizes all columns by adjusting them to fit in the longest text in each column. This is a quick method of applying AutoSizeColumn() for every column in the grid. Clean all cells in the grid subject to the given CleanOptions, optionally specifying a range of cells or a rectangular region.

Cleans all cells in the grid subject to the given CleanOptions, optionally specifying a range of cells or a rectangular region. See for more information.

Some examples:

  • Clean all cells: grid.Clean([]); (the same as grid.clean)
  • Clean all non fixed cells: grid.Clean([gzNormal]);
  • Clean all cells but don't touch grid column headers: Grid.Clean([gzNormal, gzFixedRows]);
Cells - the text content of a cell or cells, indexed by aCol, aRow Cols - get or set a list of strings for column names as specified by the index The Objects present in the specified cell Rows - gets or sets a list of strings for row names as specified by index HeaderHotZones - the header zones corresponding to the position of the mouse cursor HeaderPushZones - the zones of the header that have been pushed down (selected) CopyToClipboard - copy a range of cells to clipboard This method will copy a range of cells into the clipboard, the cells values are TAB separated. The range is defined based on optional AUseSelection parameter which is false by default and which means the range is set to the whole grid, including fixed cols/rows. If AUseSelection is true, the range of cells is set to current How to use Grids including StringGrids, DrawGrids and DbGrids

Customizing grids

Grid are components derived from the TCustomControl class and don't have a native widget associated with them, so they are not restricted by the look of the current interface theme. This can be both an advantage and a disadvantage: usually programmers want to create a uniform-look application. Lazarus grids are flexible enough to allow programmers to make them look similar to other native controls; alternatively they can customize the grid to obtain almost the same look in any platform or widget interface (with the exception of scrollbars, whose look is still determined by the current theme).

Some properties can affect the way the grid looks by acting when the cell is about to be painted in PrepareCanvas/OnPrepareCanvas by changing default canvas properties like brush color or font. Following is a list of such properties:

Properties and Events for customizing grids
Property Meaning
AlternateColor The user can change the background color that appears on alternate rows. This is to allow easy reading of grid rows data.
Color Sets the primary color used to draw non fixed cells' background.
FixedColor The color used to draw fixed cells' background.
Flat Eliminates the 3d look of fixed cells.
TitleFont Font used to draw the text in fixed cells.
TitleStyle

Changes the 3D look of fixed cells. There are 3 settings:

  • tsLazarus The default look
  • tsNative Tries to set a look that is in concordance with current widgetset theme.
  • tsStandard A more contrasted look, like Delphi grids.
AltColorStartNormal (Boolean). If true, alternate color is always in the second row after fixed rows; the first row after fixed rows will always be the default color. If false, default color is set to the first row as if there were no fixed rows.
BorderColor Sets the grid's border color used when Flat=True and BorderStyle=bsSingle;
EditorBorderStyle If set to bsNone under Windows the cell editors will not have the border, like in Delphi; set to bsSingle by default because the border can be theme specific in some widgetsets and to allow a uniform look.
FocusColor The color used to draw the current focused cell if UseXORFeatures is not set; by default this is clRed.
FocusRectVisible Turns on/off the drawing of focused cell.
GridLineColor Color of grid lines in non fixed area.
GridLineStyle Pen style used to draw lines in non fixed area, possible choices are: psSolid, psDash, psDot, psDashDot, psDashDotDot, psinsideFrame, psPattern, psClear; default is psSolid.
SelectedColor Color used to draw cell background on selected cells.
UseXORFeatures If set, focus rect is drawn using XOR mode so it should make visible the focus rect in combination with any cell color background. It also affects the way that moving columns look.
DefaultDrawing (Boolean). Normally the grids prepare the grid canvas using some properties according to the kind of cell that is being painted. If the user has written an OnDrawCell event handler, DefaultDrawing (if set) also paints the cell background; if the user is taking full responsibility for drawing the cell it is better to turn off this property so painting is not duplicated. In a StringGrid, if DefaultDrawing is set it draws the text in each cell.
AutoAdvance Where the cell cursor will go when pressing enter or tab/shift tab, or after editing.
ExtendedColSizing If true, the user can resize columns, not just at the headers, but anywhere along the column's height.

Other properties that also affect the grid's look:

Options: This property is a set of zero or more choices, with some elements that enable diverse functionality but others that are related directly with grid's look. Options can be set at designtime or runtime.

  • goFixedVertLine, goFixedHorzLine: draws a vertical or horizontal line respectively, delimiting cells or columns in the fixed area; active by default.
  • goVertLine, goHorzLine: the same as previous, but for the normal browseable area. A grid can be made to simulate a listbox by unsetting both of these options.
  • goDrawFocusSelected: if this option is enabled, a selection background is painted in the focused cell in addition to the focused dotted rectangle (note this doesn't work yet when the goRowSelect option is set; in such case the row is always painted as if goDrawFocusSelected is set)
  • goRowSelect: selects the full row instead of individual cells
  • goFixedRowNumbering: if set, grid will do numbering of rows in first fixed column
  • goHeaderHotTracking: if set, the grid will try to show a different look when the mouse cursor is over any fixed cell. In order for this to work, desired cell zone needs to be enabled with the property HeaderHotZones. Try combining this option with property TitleStyle= tsNative to get themed hot tracking look.
  • goHeaderPushedLook: if set, this option enables a pushed look when clicking any fixed cell. The zone of "pushable" cells is enabled using HeaderPushedZones property.

Description of grid's drawing process

Like other custom controls, the grid is drawn using the paint method. In general terms the grid is drawn by painting all rows, and each row by painting its individual cells.

The process is as follow:

  • First the visible cells area is determined: each row is tested to see if it intersects the canvas clipping region; if it's ok, then the visible area is painted by drawing columns of each row.
  • The column and row values are used to identify the cell that is about to be painted and again each column is tested for intersection with the clippling region; if everything is ok, some additional properties like the cell's rectangular extent and visual state are passed as arguments to the DrawCell method.
  • As the drawing process is running, the visual state of each cell is adjusted according to grid options and position within grid. The visual state is retained in a variable of type TGridDrawState which is a set with following elements:

    gdSelected The cell will have a selected look.
    gdFocused The cell will have a focused look.
    gdFixed Cell have to be painted with fixed cell look.
    gdHot the mouse is over this cell, so paint it with hot tracking look
    gdPushed the cell is being clicked, paint it with pushed look
  • DrawCell. The DrawCell method is virtual and may be overriden in descendent grids to do custom drawing. The information passed to DrawCell helps to identify which particular cell is being painted, the physical area occupied on the screen and its visible status. See DrawCell reference for details. For each cell the following occurs:

    • PrepareCanvas. If the DefaultDrawing property is set, the grid canvas is setup with default properties for brush and font based on current visual state. For several design and runtime properties, the text alignment is set to match programmer selection in custom columns if they exists. If DefaultDrawing is false, brush color is set to clWindow and Font color to clWindowText, the text alignment is set with grids defaultTextStyle property value.
    • OnPrepareCanvas. If the programmer wrote an event handler for the OnPrepareCanvas event, it is called at this point. This event can be used for doing simple customization like changing a cell's background color, font's properties like color, fontface and style, Text layout like different combinations of left, center, top, bottom, right alignment, etc. Any change made to the canvas for a particular cell in this event would be lost, because the next cell drawing will reset canvas again to a default state. So it's safe doing changes only for a particular cell or cells and forget about it for the rest. Using this event sometimes helps to avoid using the OnDrawCell grid event, where users would be forced to duplicate the grid's drawing code.
    • OnDrawCell. Next, if no handler for the OnDrawCell event was specified, the grid calls the DefaultDrawCell method which simply paints the cell background using the current canvas brush color and style. If the OnDrawCell handler exists, the grid first paints the cell background, but only if the DefaultDrawing property was set; then it calls the OnDrawCell event to do custom cell painting. Usually programmers want to do custom drawing only for particular cells, but standard drawing for others: in this case, they can restrict custom operation to certain cell or cells by looking into ACol, ARow and AState arguments, and for other cells simply call the DefaultDrawCell method and let the grid to take care of it.
    • Text. At this point, if the DefaultDrawing property is true, the cell's text content is painted (only for TStringGrid) .
    • Grid lines The last step for each cell is to paint the grid lines: if grid options goVertLine, goHorzLine, goFixedVertLine and goFixedHorzLine are specified the cell grid is drawn at this point. Grids with only rows or only cols can be obtained by changing these options. If the programmer elected to have a "themed" look it is done at this point also (see property TitleStyle).
    • FocusRect When all columns of the current row have been painted it is time to draw the focus rectangle for the current selected cell or for the whole row if the goRowSelect option is set.

Grid's cell selection

The location of a grid's current (focused) cell (or row) can be changed using keyboard, mouse or through code. In order to change cell focus successfully to another position, we must test the target position to see if it is allowed to receive cell focus. When using the keyboard, AutoAdvance performs part of the process by finding what should be the next focused cell. When using mouse clicks or moving by code, focus will not move from the current cell unless the target cell is permitted to receive focus.

The grid calls SelectCell to see if a cell is focusable: if this function returns true, then the target cell identified with arguments aCol and aRow is focusable (the current implementation of TCustomGrid simply returns true). TCustomDrawGrid and hence TDrawGrid and TStringGrid override this method and check first if a cell is any wider than 0; normally you don't want a 0 width cell selected so a cell with this characteristics is skipped automatically in the process of finding a suitable cell. The overriden method SelectCell also calls the user configurable event OnSelectCell: this event receives the cell coordinates as arguments and always returns a default result of True.

Once a cell is known to be focusable and we are sure a movement will take place, the method BeforeMoveSelection is called; this in turns triggers the OnBeforeSelection event. This method's arguments are the coordinates for the new focused cell; at this point any visible editor is hidden too. The "before" word means that selection is not yet changed and current focused coordinates can be accessed with grid.Col and grid.Row properties.

After that, the internal focused cell coordinates are changed and MoveSelection is called; this method's purpose (if set) is to trigger the OnSelection event (this is a notification that the focused cell has changed and the new cell coordinates are available through grid.row and grid.col properties).

Note that is not good to use the OnSelectCell event to detect cell focus changes, as this event will be triggered several times even for the same cell in the process of finding a suitable cell. Is better to use OnBeforeSelection or OnSelection events for this purpose.

Using cell editors

Users can specify what editor will be used for a cell using one of two methods.

  1. Using a custom column and selecting the ButtonStyle property of the column. In this method the user can select the style of the editor that will be shown. Available values are: cbsAuto, cbsEllipsis, cbsNone, cbsPickList, cbsCheckboxColumn.
  2. Using the OnSelectEditor grid event. Here the user specifies in the Editor parameter which editor to use for a cell identified by aCol, ARow in a TCustomDrawGrid derived grid or TColumn in TCustomDBGrid. The public EditorByStyle() function takes as parameter one of the following values: cbsAuto, cbsEllipsis, cbsNone, cbsPickList, cbsCheckboxColumn.
    This method takes precedence over the first one using custom columns. A Custom cell editor can be specified here, with values specific to the cell, row or column.

Description of editor styles

The following is a description of the editor styles. They are enumerated values of type TColumnButtonStyle and so they are prefixed by 'cbs'. This type was used to remain compatible with Delphi's DBGrid.

  • cbsAuto This is the default editor style for TCustomGrid derived grids. The TStringCellEditor derived from TCustomMaskEdit is specialized to edit single line strings and is used by default in TStringGrid and TDrawGrid. When using Custom Columns, if the programmer filled the Column's PickList property, this behaves as if cbsPickList editor style was set. For a TCustomDBGrid that has a field of type boolean, it behaves as if cbsCheckBoxColumn editor style was specified. This is the recommended value for Custom Cell Editors. TODO: related OnEditingDone.
  • cbsEllipsis This editor style is the most generic one. A button with ellipsis (...) appears in the editing cell and the programmer can use the OnEditButtonClick grid event to take any programmed action when the user presses the button. For example a calendar dialog could pop up to allow the user to select a specific date, a file open dialog could appear to find files, or a calculator could appear so the user could enter the numeric result of calculations, etc.

    • OnEditButtonClick is just a notification, to find out in which cell a button has been clicked by taking a look at the grid.Row and grid.Col properties.
    • A DBGrid has specific properties to retrieve the active column or field and because this event occurs in the active record, it could update the information in the active field.
    • This editor style is implemented using TButtonCellEditor, a direct descendant of TButton.
  • cbsNone This editor style instructs the grid not to use any editor for a specific cell or column; it behaves then, as if the grid were readonly for such a cell or column.
  • cbsPickList Used to present the user with a list of values that can be entered. This editor style is implemented using TPickListCellEditor, a component derived from TCustomComboBox. The list of values that are shown is filled in one of two ways depending on the method used to select the editor style.
    When using custom columns, programmers can enter a list of values using the column's PickList property. [FOR BEGINNERS: TODO: exact procedure to edit the list]
  • cbsCheckboxColumn This editor style is at the moment only available in TDBGrid. If a field's contents associated with the column are restricted to a pair of values, for example, yes-no, true-false, on-off, 1-0, etc then cbsCheckboxColumn is used to modify the apearance of a column by using a checkbox representation that the user can toggle by using a mouse click or pressing the SPACE key.

    • If a columns' ButtonStyle property is set to cbsAuto and DBGrid detects that the field associated with the column is a boolean field, then the grid uses this editor style automatically. This automatic selection can be disabled or enabled using DBGrid's OptionsExtra property; setting dgeCheckboxColumn element to false disables this feature.
    • The values that are used to recognize the checked or unchecked states are set in a column's properties ValueChecked and ValueUnchecked.
    • At any moment, the field value can be in one to three states: Unchecked, Checked or Grayed.
Todo: samples of what can be made and what to leave for OnDrawCell?
msg_SetPos - issues message for specifying position msg_SetBounds - issues message for specifying bounds msg_Ready - issues message when ready msg_SetPos - issues a message to specify the position TEditorItem - a single item on which a Composite Cell Editor operates The Editor to be used for this item Align - how this item is to be aligned ActiveControl - returns True if this item is part of an active control TCompositeCellEditor - a general purpose editor for cells in a grid msg_GetValue - issues a message to find the value msg_SetGrid - issues message for specifying grid msg_SetValue - issues a message to specify the value msg_SetBounds - issues message for specifying bounds msg_SetMask - issues message for specifying mask msg_SelectAll - issues message for Selecting All CMControlChange - issues Control Message for a change in a control msg_SetPos - issues a message to specify the position SendChar - transmits the specified character and returns an integer status result 0 - failure, 1 - success AddEditor - adds the specified Editor with the given alignment and specified ActiveControl propery ImageIndex - the index for any image to be used in the title (default=0, ie no image) ImageLayout - the layout to use for any image in the title AdjustEditorBounds - method to adjust the editor's bounds to include a new row and column DrawColumnTitleImage - draw the title image of the specified column EditingAllowed - Returns true if grid and current column allow editing TitleImageList - the list of images to be used with the titles GetValueChecked - returns a checked value as a string GetValueUnchecked - returns an unchecked value as a string ValueChecked - a string value of a checked item ValueUnchecked - a string value of an unchecked item DrawGridCheckboxBitmaps - draws checkbox bitmaps in the nominated rectangle with the specified checkbox state OnUserCheckboxBitmap - event handler for a user accessing a checkbox bitmap GetCheckBoxState - returns the state of the checkbox at the specified position SetCheckboxState - specifies the state of the checkbox in the nominated cell ToggleCheckbox - toggles checkbox state between checked and unchecked OnGetCheckboxState - event handler for finding checkbox state OnSetCheckboxState - event handler for specifying checkbox state GetDefaultValueChecked - returns the default value for a checked column GetDefaultValueUnchecked - returns the default value for an unchecked column