1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Highlight Non-Focused DBGrid Selected Row

By Zarko Gajic, About.com

Highlight Selected Row in a Non-Focused DBGrid

Highlighted Selected Row in a Non-Focused DBGrid

In Delphi database applications one of the mostly used controls is the TDBGrid.
TDBGrid displays and manipulates records from a dataset in a tabular grid.

In scenarios where you have two DBGrid controls on the same form displaying data for a master-detail database relationship like Customer -> Orders, for a selected record/row in the "master" grid only related records are displayed in the "child" grid.

When "dgRowSelect" is included in the Options property, when a user selects a row in a grid, the entire row gets selected.

As soon as the grid looses the focus, the selected row does no longer appear selected (beside the little black triangle in the first column - if dgIndicator is included in Options).

This leads to the next problem: when the user selected a child row in the "child" dbgrid, the related record in the "master" grid is no more selected - highlighted.

To enhance user experience you might want to highlight the selected row in the DBGrid even when the DBGrid does NOT have the focus.

You need to handle the OnDrawColumnCell event to make the selected record appear highlighted:

//DBGrid1.OnDrawColumnCell event handler
procedure TDBGridForm.DBGrid1DrawColumnCell(
   Sender: TObject;
   const Rect: TRect;
   DataCol: Integer;
   Column: TColumn;
   State: TGridDrawState) ;
begin
   if NOT DBGrid1.Focused then
   begin
     if (gdSelected in State) then
     begin
       with DBGrid1.Canvas do
       begin
         Brush.Color := clHighlight;
         Font.Style := Font.Style + [fsBold];
         Font.Color := clHighlightText;
       end;
     end;
   end;

   DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State) ;
end;
When the DBGrid1 (presume "master" grid) does not have the focus (presume switched to the "child" grid), we "paint" the selected row (gdSelected in State) as if the grid has the focus using the predefined clHighlight color for row background and clHighlightText for the font color. To make it even more visible, we also apply "Bold" for the font.

Yes, simpler than it sounded :)

Delphi tips navigator:
» Allow Only One Application Execution Per Windows Session
« How to Declare and Initialize Constant Arrays in Delphi

More Delphi Programming Quick Tips

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Highlight Non-Focused DBGrid Selected Row in Delphi Database applications

©2008 About.com, a part of The New York Times Company.

All rights reserved.