2012-08-01

【Delphi】自動調整 DBGrid 欄寬

寫在 DBGrid OnDrawColumnCell,如下:

 
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    with DBGrid1 do
    begin
        if not VarIsNull(Column.Field.Value) then
            if Column.Width<(4+Canvas.TextWidth(Column.Field.DisplayText)) then
                Column.Width := 4 + Canvas.TextWidth(Column.Field.DisplayText);
    end;
end;
 
4 的用意是要讓欄寬比顯示字串所需的寬度再大些, 才不會看起來很擠, 可視實際情況調整數值.

沒有留言:

張貼留言