Author: Tomas Rutkauskas
Using Delphi 4 and a TStringGrid component: How do I highlight the entire row in
the grid where the cursor is currently? In other words, if the user clicks their
mouse cursor on row 3, I want the entire row 3 to be highlighted pale yellow. When
they then move the cursor to row 6, I want row 3 to revert back to white, and then
have the entire row 6 turn pale yellow. Please note that I must be able to also
edit the contents of any cell in the highlighted row.
Answer:
You can achieve this fairly easily with a combination of handlers for the
OnSelectCell and OndrawCell events of the grid:
1 type2 TGridCracker = class(TStringGrid);
3 {required to access protected method InvalidateRow}4 5 procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
6 var CanSelect: Boolean);
7 begin8 with TGridCracker(Sender as TStringGrid) do9 begin10 InvalidateRow(Row);
11 InvalidateRow(aRow);
12 end;
13 end;
14 15 procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
16 Rect: TRect; State: TGridDrawState);
17 var18 grid: TStringGrid;
19 begin20 if gdFixed in State then21 Exit;
22 grid := Sender as TStringGrid;
23 if grid.Row = aRow then24 begin25 with Grid.Canvas.Brush do26 begin27 Color := $C0FFFF; {pale yellow}28 Style := bsSolid;
29 end;
30 grid.Canvas.FillRect(Rect);
31 grid.Canvas.Font.Color := clBlack;
32 grid.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, grid.Cells[acol, arow]);
33 Grid.Canvas.Brush := grid.Brush;
34 end;
35 end;