Dynamically size DBGrid columns

1.8k views Asked by At

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.

0

There are 0 answers