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

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

    EDITED:

    My first code was about fit the columns inside the grid with, with this new code, AutoSizeColumns reads the records to calc the width of each column until MaxRows or Dataset.Eof:

    class function TDBGridHelper.AutoSizeColumns(DBGrid: TDBGrid; const MaxRows: Integer = 25): Integer;
    
    var
      DataSet: TDataSet;
      Bookmark: TBookmark;
      Count, I: Integer;
      ColumnsWidth: array of Integer;
    begin
      SetLength(ColumnsWidth, DBGrid.Columns.Count);
      for I := 0 to DBGrid.Columns.Count - 1 do
        if DBGrid.Columns[I].Visible then
          ColumnsWidth[I] := DBGrid.Canvas.TextWidth(DBGrid.Columns[I].Title.Caption + '   ')
        else
          ColumnsWidth[I] := 0;
      if DBGrid.DataSource <> nil then
        DataSet := DBGrid.DataSource.DataSet
      else
        DataSet := nil;
      if (DataSet <> nil) and DataSet.Active then
      begin
        Bookmark := DataSet.GetBookmark;
        DataSet.DisableControls;
        try
          Count := 0;
          DataSet.First;
          while not DataSet.Eof and (Count < MaxRows) do
          begin
            for I := 0 to DBGrid.Columns.Count - 1 do
              if DBGrid.Columns[I].Visible then
                ColumnsWidth[I] := Max(ColumnsWidth[I], DBGrid.Canvas.TextWidth(
                  DBGrid.Columns[I].Field.Text));
            Inc(Count);
            DataSet.Next;
          end;
        finally
          DataSet.GotoBookmark(Bookmark);
          DataSet.FreeBookmark(Bookmark);
          DataSet.EnableControls;
        end;
      end;
      Count := 0;
      for I := 0 to DBGrid.Columns.Count - 1 do
        if DBGrid.Columns[I].Visible then
        begin
          DBGrid.Columns[I].Width := ColumnsWidth[I];
          Inc(Count, ColumnsWidth[I]);
        end;
      Result := Count - DBGrid.ClientWidth;
    end;
    

    I call it in the DataSet.AfterOpen event:

    TGridHelper.AutoSizeColumns(MyDBGrid);
    

提交回复
热议问题