0

How can I calculate width for columns in dbgrid if a few or them are static.?For example the first three need to have static widths and five remaining need to be resized.

Goal is to make the check-boxes turn on or off visibility and change columns width to fit grid.

Image

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject;
      const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  i:integer;
  column1: integer;
  width2 : integer;
  width1: integer;
begin
  width1 := 1;
  column1:=-3;
  for i := 0 to DBGrid1.Columns.Count - 1 do
  begin
    width1 := width1 + DBGrid1.Columns[i].Width + 1;
    if DBGrid1.Columns[i].Visible then
       column1:=column1 +1;
  end;
  width2:=(80 div column1);
  if ((width1 < DBGrid1.ClientWidth - width2) or (width1 > DBGrid1.ClientWidth +width2)) then
  begin
    DBGrid1.Columns[0].Width:=(DBGrid1.ClientWidth)*10 div 100;
    DBGrid1.Columns[1].Width:=(DBGrid1.ClientWidth)*5 div 100;
    DBGrid1.Columns[2].Width:=(DBGrid1.ClientWidth)*(100-colum1n*width2-15) div 100;
    DBGrid1.Columns[3].Width:=(DBGrid1.ClientWidth)*width2 div 100;
    DBGrid1.Columns[4].Width:=(DBGrid1.ClientWidth)*width2 div 100;
    DBGrid1.Columns[5].Width:=(DBGrid1.ClientWidth)*width2 div 100;
    DBGrid1.Columns[6].Width:=(DBGrid1.ClientWidth)*width2 div 100;
    DBGrid1.Columns[7].Width:=(DBGrid1.ClientWidth)*width2 div 100;
  end;

That's the code I use at the moment but its working kinda slow.

Thanks in advance.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Ledzouz
  • 59
  • 8
  • 2
    The event is meant for *drawing* onto a cell and not for anything else. You need to adjust the grid elsewhere for example when the grid resized. – kobik Dec 24 '16 at 06:20
  • Correct me if I'm wrong but there is no on grid resized event. – Ledzouz Dec 24 '16 at 07:38
  • 1
    No. but `TControl` has (protected) `OnResize` event. you can declare `type TDBGridAccess = class(TDBGrid);` and then `TDBGridAccess(DBGrid1).OnResize := MyGridResizeEvent`. It also has a dynamic `Resize` method which you can override with a descendent or interposer class. You also need to handle when columns are resized. see: http://stackoverflow.com/questions/15063680/where-the-tdbgrid-columns-resize-event-was-triggered – kobik Dec 24 '16 at 08:38

0 Answers0