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

前端 未结 8 1822
天命终不由人
天命终不由人 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:30

    Hello use this procedure.

    Procedure AutoSizeColDBGrid(DBGrid:TDBGrid);
    var i, ColWidth, ColTextWidth:integer;
    begin
     if DBGrid.DataSource.DataSet.Active then
       begin
         DBGrid.DataSource.DataSet.DisableControls;
         for i:= 0 to DBGrid.Columns.Count-1 do
           begin
             ColWidth:=DBGrid.Canvas.TextWidth(DBGrid.Columns[i].Field.DisplayLabel);
             DBGrid.DataSource.DataSet.First;
           while not DBGrid.DataSource.DataSet.EOF do
            begin
           ColTextWidth:=DBGrid.Canvas.TextWidth(DBGrid.Columns[i].Field.DisplayText);
              if (ColTextWidth > ColWidth) then
                begin
                  ColWidth := ColTextWidth;
                end;
              DBGrid.DataSource.DataSet.Next;
           end;{while}
           DBGrid.Columns[i].Width:=ColWidth+10;
         end;{for}
    DBGrid.DataSource.DataSet.EnableControls;
    DBGrid.DataSource.DataSet.First;
    end;
    end;
    

提交回复
热议问题