Author: Tomas Rutkauskas
How to highlight the current cell in a TStringGrid
Answer:
You solve your problem by using a handler for the grids OnDrawCell event. There you
draw both cell background and text when the cell is in the column or row of the
selected cell. You also need a handler for OnSelectCell. Here you invalidate the
row and column for the old selected cell (still indicated by the grids Col and Row
property) and then you invalidate the row and column for the newly selected cell
(indicated by the handlers aCol and arow parameters). The TStringGrid class
inherits some protected methods from its ancestors which you need for this task.
These are InvalidateRow and InvalidateCol. You get at them using a cracker class.
1 type2 TGridCracker = class(TStringgrid);
3 4 procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
5 Rect: TRect; State: TGridDrawState);
6 var7 grid: TStringGrid;
8 begin9 grid := Sender as TStringGrid;
10 ifnot (gdfixed in State) and ((grid.row = arow) or (grid.col = acol)) then11 begin12 with grid.canvas do13 begin14 brush.color := clYellow;
15 if gdSelected in State then16 Font.color := clBlue
17 else18 Font.color := clBlack;
19 Fillrect(rect);
20 TextRect(Rect, Rect.left + 2, rect.top + 2, grid.Cells[acol, arow]);
21 end;
22 end;
23 end;
24 25 procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
26 ARow: Integer; var CanSelect: Boolean);
27 begin28 with TGridCracker(Sender as TStringGrid) do29 begin30 {redraw column and row if currently selected cell}31 Invalidaterow(row);
32 Invalidatecol(col);
33 {redraw column and row of new selected cell}34 Invalidaterow(arow);
35 Invalidatecol(acol);
36 end;
37 end;