Search code examples
delphidevexpressdelphi-xe5dbgrid

How to fire grid double right border click event by code on delphi xe5?


I m using Dev Express DBGrid component, I want to scale my column to fit my rows text so I used :

cxView.ApplyBestFit();

That works but somehow too slow, so I did some search and I found this post on Dev Express Website but this don't help me much. So i started observing the grid interactivity what lead me to discover that if I double click all right borders of the grid one after other the grid will scale perfectly and quickly as you see in the two pictures below :

that was the 4th right border click

then i continue to the last border to get this result :

As you see is well scaled

I m trying desperate to fire this double clicks by code but I lack experience on Delphi and Dev Express. So how to fire this event successively in all columns one by one.

Thank you


Solution

  • The code below will do the same as double-clicking the rhs of each header cell.

    Code:

    procedure TForm1.ApplyBestFits;
    var
      i : Integer;
    begin
      try
        cxGrid1DBTableView1.BeginUpdate;
        for i := 0 to cxGrid1DBTableView1.ColumnCount - 1 do begin
          cxGrid1DBTableView1.Columns[i].ApplyBestFit;
        end;
      finally
        cxGrid1DBTableView1.EndUpdate;
      end;
    end;
    

    However, I'm not sure that as it stands it is a complete solution to your problem. In my test case, with 100 columns and 2000 data rows, it takes a second or two to execute, which I imagine is much slower than you were hoping. So it may need some optimization.

    One obvious optimization would be to only call cxGrid1DBTableView1.Columns[i].ApplyBestFit for columns that are within the client rect of the DBTableView. Another might be to restrict the number of rows in the dataset connected to the tableview to a lower number. For instance, the following only calls ApplyBestFit to columns whose Left coordinate is within the width of the cxGrid.

    procedure TForm1.ApplyBestFits;
    var
      i : Integer;
      ALeft : Integer;
      ACol : TcxGridColumn;
    begin
      try
        ALeft := 0;
        cxGrid1DBTableView1.BeginUpdate;
        //  Process only the visible columns whose Left properties
        //  are within the width of the grid
        for i := 0 to cxGrid1DBTableView1.VisibleColumnCount - 1 do begin
          ACol := cxGrid1DBTableView1.VisibleColumns[i];
          ACol.ApplyBestFit;
          Inc(ALeft, ACol.Width);
          if ALeft > cxGrid1.Width then
            Break;
        end;
      finally
        cxGrid1DBTableView1.EndUpdate;
      end;
    end;