假设该组件有若干列,有的列希望整列数据显示为靠左,有的列希望显示为靠右,有的列希望居中显示,有的列希望数字保留3位小数。希望在运行中设置,如何做到呢?谢谢!

解决方案 »

  1.   

    在StringGrid的DrawCell事件中添加类似的代码就可以了:
    VAR  vCol, vRow : LongInt;
    begin 
     vCol := ACol;
     vRow := ARow;
      WITH Sender AS TStringGrid, Canvas DO  
      IF vCol = 2 THEN BEGIN ///对于第2列设置为右对齐  
        SetTextAlign(Handle, TA_RIGHT); 
         FillRect(Rect);  
        TextRect(Rect, Rect.RIGHT-2, Rect.Top+2, Cells[vCol, vRow]); 
       END;
    end;
      

  2.   

    procedure Tgegongsi_Form.StringGrid1DrawCell(Sender: TObject; ACol,
      ARow: Integer; Rect: TRect; State: TGridDrawState);
    var
      CellStr: String;
      Mode,CellLen: Integer;
    begin
      //①先清除CELL
      StringGrid1.Canvas.FillRect(Rect);  CellStr := StringGrid1.Cells[ACol,ARow];
      //②根据文字長度自動調節列寛
      CellLen := advStringGrid1.Canvas.TextWidth(CellStr)+3;
      if (CellLen>advStringGrid1.ColWidths[ACol]) then
        advStringGrid1.ColWidths[ACol] := CellLen;
      if Acol = 0 then
         stringgrid1.ColWidths[Acol]:=30;
                     
      //③底色設定
      if ARow>0 then begin
        if ARow mod 2 = 0 then
          StringGrid1.Canvas.Brush.Color := $00DBDBDB
        else
          StringGrid1.Canvas.Brush.Color := clWhite;
        stringGrid1.Canvas.TextRect(Rect,Rect.Left,Rect.Top,'');
           //④文字排版
      if ARow=0 then begin
        StringGrid1.Canvas.Font.Color := clBlue; //可設定字体的顔色、大小
        Mode := DT_CENTER         //調整左右
      end
      else begin
        StringGrid1.Canvas.Font.Color := clWindowText;
        Mode := DT_LEFT;
        Rect.Left := Rect.Left+2; //微調(使字不圧左側的線)
      end;
     Rect.Top := Rect.Top+1;     //調整上下  DrawText(StringGrid1.Canvas.Handle,PChar(CellStr),Length(CellStr),Rect,Mode);
    end;
    看看这个例子吧