Mega Code Archive

 
Categories / Delphi / ADO Database
 

How to Highlight Non Focused DBGrid Selected Row in Delphi Database applications

Title: How to Highlight Non-Focused DBGrid Selected Row in Delphi Database applications 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 :)