简体   繁体   中英

How to get the length of the longest entry on TDBGrid Columns

I have a TDBGrid component called grMain. I need to know length of value of the longest entries of Column which retrivied on grMain to adjust the minimal width of the form holding the grMain.

How to get the length of the longest entry on TDBGrid Columns?

Thanks in advance.

Something like that ...

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);
        ZeroMemory(@a[0],SizeOf(Integer)*Length(a));
        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 + C_Add;
                    end;

                end;
            ds.Next;
          end;
        for I := 0 to Grid.Columns.Count - 1 do Grid.Columns[i].Width := a[i];
        ds.GotoBookmark(bm);
        finally
          ds.FreeBookmark(bm);
          ds.EnableControls;
        end;
      end;
end;

procedure TForm1.Button1Click(Sender: TObject);

begin
  FitGrid(DBgrid1)
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM