How to auto fit/scale DBGrid's (or other similar) columns widths according to its contents?

前端 未结 8 1825
天命终不由人
天命终不由人 2021-01-04 14:11

I am trying to make a frame with a DBGrid that will serve for more than 10 tables with half of its fields as defaults, and other fields exclusive for each table

8条回答
  •  悲哀的现实
    2021-01-04 14:29

    What you have to do is to use the grid's canvas to measure the contents of each column and set the column's width accordingly. You can either iterate through the dataset or use the OnColumnDraw-Event to adjust the width on the fly.

    Here's a sample (I had to use an offset of 5 pixels)

    procedure TForm7.DBGridDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    Var
      w : Integer;
    
    begin
      w := 5+DBGrid.Canvas.TextExtent(Column.Field.DisplayText).cx;
      if w>column.Width then Column.Width := w;
    end;
    
    procedure TForm7.FormActivate(Sender: TObject);
    Var
      i : Integer;
    
    begin
      // Initialize width
      for I := 0 to DBGrid.Columns.Count - 1 do
        DBGrid.Columns[i].Width := 5 + DBGrid.Canvas.TextWidth(DBGrid.Columns[i].title.caption)
    end;
    

提交回复
热议问题