Mirror

Align cells in a TStringGrid (Views: 102)


Problem/Question/Abstract:

I need to align cells in a StringGrid - first cell to the left, second to the right and so on ...

Answer:

procedure WriteText(ACanvas: TCanvas; const ARect: TRect; DX, DY: Integer;
  const Text: string; Format: Word);
var
  S: array[0..255] of Char;
  B, R: TRect;
begin
  with ACanvas, ARect do
  begin
    case Format of
      DT_LEFT:
        ExtTextOut(Handle, Left + DX, Top + DY, ETO_OPAQUE or ETO_CLIPPED,
          @ARect, StrPCopy(S, Text), Length(Text), nil);
      DT_RIGHT:
        ExtTextOut(Handle, Right - TextWidth(Text) - 3, Top + DY,
          ETO_OPAQUE or ETO_CLIPPED, @ARect, StrPCopy(S, Text), Length(Text), nil);
      DT_CENTER:
        ExtTextOut(Handle, Left + (Right - Left - TextWidth(Text)) div 2, Top + DY,
          ETO_OPAQUE or ETO_CLIPPED, @ARect, StrPCopy(S, Text), Length(Text), nil);
    end;
  end;
end;

procedure TBEFStringGrid.DrawCell(Col, Row: Longint; Rect: TRect;
  State: TGridDrawState);
var
  procedure Display(const S: string; Alignment: TAlignment);
  const
    Formats: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
  begin
    WriteText(Canvas, Rect, 2, 2, S, Formats[Alignment]);
  end;
begin
  {test the Col and Row arguments here and format the cells as you want}
  case Row of
    0: { Center column headings }
      if (Col < ColCount) then
        Display(Cells[Col, Row], taCenter)
      else
        { Right justify all other entries }
        Display(Cells[Col, Row], taRight);
  end;
end;

<< Back to main page