Recent

Author Topic: [CLOSED] DBGrid Autosize  (Read 907 times)

egsuh

  • Hero Member
  • *****
  • Posts: 1273
[CLOSED] DBGrid Autosize
« on: July 17, 2020, 07:39:19 am »
I'd like to show DBGrid in the way that last column fill to the end, with previous columns are auto fit to each width (this is done by setting dgAutoSizeColumns true).

But once I set property AutoFillColumns=true, then all columns are divided evenly.  Is there any way that I can set only the last column take to the end?

« Last Edit: July 18, 2020, 07:46:11 am by egsuh »

emilt

  • New Member
  • *
  • Posts: 26
Re: DBGrid Autosize
« Reply #1 on: July 17, 2020, 08:39:45 am »
Maybe you should check the TGridColumn.SizePriority property.

balazsszekely

  • Guest
Re: DBGrid Autosize
« Reply #2 on: July 17, 2020, 08:49:13 am »
Hi egsuh,

Please test the following code, but first set dgAutoSizeColumns to false. In this example the last column is 4, you can change it according to your needs.
Code: Pascal  [Select][+][-]
  1. type
  2.  
  3.   TForm1 = class(TForm)
  4.   //...
  5.   procedure FormCreate(Sender: TObject);
  6.   procedure SQLQuery1AfterOpen(DataSet: TDataSet);
  7.   private
  8.     procedure AutoSnapColumn(AGrid: TDBGrid; AColumn: Integer);
  9.     procedure GridResize(Sender: TObject);
  10.   public
  11.  
  12.   end;
  13.  
  14.  
  15. implementation
  16.  
  17. procedure TForm1.FormCreate(Sender: TObject);
  18. begin
  19.   DBGrid1.OnResize := @GridResize;
  20. end;
  21.  
  22. procedure TForm1.GridResize(Sender: TObject);
  23. begin
  24.   AutoSnapColumn(DBGrid1, 4);
  25. end;
  26.  
  27. procedure TForm1.SQLQuery1AfterOpen(DataSet: TDataSet);
  28. begin
  29.   AutoSnapColumn(DBGrid1, 4);
  30. end;
  31.  
  32. procedure TForm1.AutoSnapColumn(AGrid: TDBGrid; AColumn: Integer);
  33. var
  34.  I: Integer;
  35.  W: Integer;
  36. begin
  37.   if AColumn > AGrid.Columns.Count - 1  then
  38.     Exit;
  39.   W := 0;
  40.   for I := 0 to AGrid.Columns.Count - 1 do
  41.     if I <> AColumn then
  42.       W := W + AGrid.Columns[I].Width;
  43.   if dgIndicator in AGrid.Options then
  44.     W := W + DEFINDICATORCOLWIDTH;
  45.   AGrid.Columns[AColumn].Width := AGrid.ClientWidth - W;
  46. end;

egsuh

  • Hero Member
  • *****
  • Posts: 1273
Re: DBGrid Autosize
« Reply #3 on: July 18, 2020, 07:45:50 am »
@GetMem,

Your approach must be a generic solution. But I solved my problem in following way.

Code: Pascal  [Select][+][-]
  1. procedure TSelectOpenCF.bdsOpenCFListAfterOpen(DataSet: TDataSet);
  2. var
  3.    pw, ti : integer;
  4. begin
  5.    pw := 30;
  6.    for ti := 0 to bdsOpenCFList.FieldCount-2 do
  7.        pw += DBGrid1.Columns[ti].Width + 2;
  8.    DBGrid1.LastColumn.Width := DBGrid1.Width - pw ;
  9. end;
  10.  

Do not ask me why 30 and 2. They just fit my case.  :D

 

TinyPortal © 2005-2018