Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

align to right a column of a stringgrid 1

Status
Not open for further replies.

DaZZleD

Programmer
Oct 21, 2003
886
US
how can i align to right a column of a stringgrid?
 
Here is a version of the routine I use (Note the reference to the Windows API function DrawText which is another way to go.):
[blue]
Code:
{Right-adjusts text in a given TRect on a given TCanvas.
Useful for handling OnDrawCell events.  See also WINAPI DrawText().}
procedure RightAdjustText( Canvas:TCanvas; Rect:TRect; Text:string );
var
  nLeft: integer;
begin
  nLeft := Rect.Left + (Rect.Right - Rect.Left) - (Canvas.TextWidth(Text)) - 2;
  if nLeft < Rect.Left then nLeft := Rect.Left;
    Canvas.TextRect( Rect, nLeft, Rect.Top+2, Text );
end;
[/color]

Here is an example of how to use it:
[blue]
Code:
{Custom formatting On DrawCell event...}
procedure TfrmMain.gridMainDrawCell(Sender: TObject; ACol,
  ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  if (ACol = 2) and (ARow > 0) then
    with gridMain do
      RightAdjustText( Canvas, Rect, Cells[ACol,ARow] );
end;
[/color]

 
This question comes up frequently. Take a look at the FAQs.

faq102-3514

Andrew
 
Andrew, It may just be a matter of taste (I certainly don't want to cross sabres with the top Forum MVP), but there are three things about the code in the FAQ which bother me.

1. The text is slammed up against the top of the cell resulting in a ragged appearance if some cells are right-adjusted and some are not.

2. If the cell width is too narrow to contain the entire text (as may happen if the user can re-size the column width), only the right-hand portion shows. I prefer to lose data from the right and keep the left-hand characters in view. But of course the specifics of the application may dictate otherwise.

3. I prefer to keep the working code separate from the logic which may be necessary for testing specific columns and/or rows on which to apply the right-adjusting effect, which is why I put the details in a procedure. (Global on a separate &quot;utilities&quot; unit which can be used by any form.)

 
Zathras,

Your three points are valid. I wrote the FAQ because the same question came up a couple of times.

I tried to keep the answer to the question fairly simple on the assumption that anyone asking it was probably new to Delphi - perhaps unaware of OnDrawCell. However, that may not be a valid basis for a FAQ.

I'll update the FAQ. Thanks for your constructive comments.

Andrew
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top