Recent

Author Topic: [SOLVED] how to RightJustify columns in a TStringGrid?  (Read 5728 times)

Hartmut

  • Hero Member
  • *****
  • Posts: 739
[SOLVED] how to RightJustify columns in a TStringGrid?
« on: October 04, 2016, 12:22:23 pm »
I want to have some columns of my TStringGrid justified to the right. I found no property for that... In the internet I found only suggestions, which write new procedures for TForm1.StringGridDrawCell() called by the string grid's OnDrawCell event. Is there really no way which is more easy like a property for that?
Thanks in advance.
« Last Edit: October 04, 2016, 01:25:06 pm by Hartmut »

wp

  • Hero Member
  • *****
  • Posts: 11830
Re: how to RightJustify columns in a TStringGrid?
« Reply #1 on: October 04, 2016, 12:30:47 pm »
TStringGrid and its ancestors do not provide a property for text alignment because there is no way how to store that information for the moment when it is needed. Instead, it introduces an event OnPrepareCanvas which is called from the DrawCell method immediately before anything is painted onto the canvas.

In order to achieve right-alignment of text set the Alignment in the TextStyle of the Canvas to taRightJustify:
Code: Pascal  [Select][+][-]
  1. procedure TForm1.StringGrid1PrepareCanvas(sender: TObject; aCol, aRow: Integer;
  2.   aState: TGridDrawState);
  3. var
  4.   ts: TTextStyle;
  5. begin
  6.   if aCol = <column to be right-aligned> then begin
  7.     ts := TStringGrid(Sender).Canvas.TextStyle;
  8.     ts.Alignment := taRightJustify;
  9.     TStringGrid(Sender).Canvas.TextStyle :=ts;
  10.   end;
  11. end;
This event is very important for modifying how a cell is painted. You can also change the font or background color here.

[EDIT]
If you work with columns there's an easier way though: Select the column in the object inspector, and set its "Alignment" to taRightJustify. This setting is valid for the entire column; the alignment of the Title can be changed by using Title.Alignment. Above solution has the advantage that individual cells can be handled separately.
« Last Edit: October 04, 2016, 12:46:39 pm by wp »

Hartmut

  • Hero Member
  • *****
  • Posts: 739
Re: how to RightJustify columns in a TStringGrid?
« Reply #2 on: October 04, 2016, 01:24:42 pm »
Thanks a lot to wp for those 2 good solutions.

 

TinyPortal © 2005-2018