Mega Code Archive

 
Categories / Delphi / VCL
 

How do I right justify text in a StringGrid

Title: How do I right justify text in a StringGrid? It is fairly easy to right justify text in a String Grid (a similar technique can be used in a Draw Grid). First you need to set the string grid DefaultDrawing property to False. Second you need to write a handler for the string grid's OnDrawCell event. The event handler should look something like: procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var text: string; WidthOfText: integer; WidthOfCell: integer; LeftOffset: integer; begin with StringGrid1 do begin text := Cells[ACol,ARow]; WidthOfText := Canvas.TextWidth(text); WidthOfCell := ColWidths[ACol]; LeftOffset := WidthOfCell - WidthOfText; Canvas.TextRect(Rect,Rect.Left+LeftOffset,Rect.Top,text); end; end; You may wish to enhance this code by changing the brush and pen properties of the string grid's canvas to introduce colour. You may also wish to centre the text vertically in the cell in which case you will find the TextHeight function useful. Andrew