2009. október 5., hétfő

Highlight the current cell in a TStringGrid


How to highlight the current cell in a TStringGrid


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.

  TGridCracker = class(TStringgrid);

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
  grid: TStringGrid;
  grid := Sender as TStringGrid;
  if not (gdfixed in State) and ((grid.row = arow) or (grid.col = acol)) then
    with grid.canvas do
      brush.color := clYellow;
      if gdSelected in State then
        Font.color := clBlue
        Font.color := clBlack;
      TextRect(Rect, Rect.left + 2, rect.top + 2, grid.Cells[acol, arow]);

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
  ARow: Integer; var CanSelect: Boolean);
  with TGridCracker(Sender as TStringGrid) do
    {redraw column and row if currently selected cell}
    {redraw column and row of new selected cell}

Nincsenek megjegyzések:

Megjegyzés küldése