Delphi coding hints and tips.
DBGrid row highlight without dgRowSelect
To get a DBGrid to highlight the current record you have to set dgRowSelect to True in the Option property of the grid. The problem then is once dgRowSelect is true you can not edit an individual field. Also right click for a popup menu or the underling dataset changes (eg insert new record) the grid will always scroll back to first field.
Below is the code required to get a grid to highlight the whole record without dgRowSelect set to true. It relies on unit friendly varibles to get at the protected properties and methods in TCustomDBGrid, the ansector of TDBGrid. By decalring a new class TFriendly=class(TCustomDBGrid) in the same unit you can reference the private bits of the class, all you have to do then is cast DBGird1 as TFriendly. The OnDrawColumnCell is used to do the actual highlighting.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, DBCtrls, Grids, DBGrids, Db, DBTables;
type
TForm1 = class(TForm)
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn;
State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
type
{expose private & protected properties & methods}
TFriendly=class(TCustomDBGrid);
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect:
TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
{cast DBGrid to a unit friendly class thus exposing all it private bits!}
with TFriendly(DBGrid1) do
begin
{Get active record within grids TDataLink. The active record will be
the current record in the dataset. Check against Row that we are
trying to Draw, -1 to offset the column headings within grid.}
if TDataLink(DataLink).ActiveRecord=Row-1
then
begin
with Canvas do
begin
{set grids canvas to win highlight colour}
Brush.Color:=clHighlight;
{now redraw the cell, but highlighted}
DefaultDrawColumnCell(Rect,DataCol,Column,State);
end;
end;
end;
end;
end.


