2010. június 8., kedd

Highlight an entire row in a TStringGrid


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.


You can achieve this fairly easily with a combination of handlers for the OnSelectCell and OndrawCell events of the grid:

  TGridCracker = class(TStringGrid);
  {required to access protected method InvalidateRow}

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);
  with TGridCracker(Sender as TStringGrid) do

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
  grid: TStringGrid;
  if gdFixed in State then
  grid := Sender as TStringGrid;
  if grid.Row = aRow then
    with Grid.Canvas.Brush do
      Color := $C0FFFF; {pale yellow}
      Style := bsSolid;
    grid.Canvas.Font.Color := clBlack;
    grid.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, grid.Cells[acol, arow]);
    Grid.Canvas.Brush := grid.Brush;

Nincsenek megjegyzések:

Megjegyzés küldése