Adjust Column width DBGrid

前端 未结 5 1942
予麋鹿
予麋鹿 2020-12-06 18:31

I have a TDBGrid. It works, but the columns shown are very large.

How can I set an \"auto-fix column width\"?

5条回答
  •  广开言路
    2020-12-06 19:15

    Minor modification of bummi's answer to insure that Title Row (Row 0) is not truncated

    procedure FitGrid(Grid: TDBGrid);
    const
      C_Add=3;
    var
      ds: TDataSet;
      bm: TBookmark;
      i: Integer;
      w: Integer;
      a: Array of Integer;
    begin
      ds := Grid.DataSource.DataSet;
      if Assigned(ds) then
      begin
        ds.DisableControls;
        bm := ds.GetBookmark;
        try
          ds.First;
          SetLength(a, Grid.Columns.Count);
          while not ds.Eof do
          begin
            for I := 0 to Grid.Columns.Count - 1 do
            begin
              if Assigned(Grid.Columns[i].Field) then
              begin
                w :=  Grid.Canvas.TextWidth(ds.FieldByName(Grid.Columns[i].Field.FieldName.).DisplayText);
                if a[i] < w  then
                   a[i] := w ;
              end;
            end;
            ds.Next;
          end;
          //if fieldwidth is smaller than Row 0 (field names) fix
          for I := 0 to Grid.Columns.Count - 1 do
          begin
            w :=  Grid.Canvas.TextWidth(Grid.Columns[i].Field.FieldName);
            if a[i] < w  then
               a[i] := w ;
          end;
    
          for I := 0 to Grid.Columns.Count - 1 do
            Grid.Columns[i].Width := a[i] + C_Add;
            ds.GotoBookmark(bm);
        finally
          ds.FreeBookmark(bm);
          ds.EnableControls;
        end;
      end;
    end;
    

提交回复
热议问题