Search code examples
delphipascaldelphi-xe7

How to adjust the column width to the content of a cell and allow to modify the width in Delphi XE7?


Good morning, I'm trying to adjust the width of the columns of a grid to its content but I also need that width can be modified manually. The grid is a TStringGrid and im using delphi XE7. I am trying to do it with the following code:

procedure gDetailDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
  vWidth : Integer;
begin
  if (FormPosition.WMaximized = True) then
  begin
    vWidth := gDetail.Canvas.TextWidth(gDetail.Cells[ACol, ARow]);
    if vWidth > aColWidthExpanded[ACol] then
      aColWidthExpanded[ACol] := vWidth+20;
    gDetail.ColWidths[ACol] := aColWidthExpanded[ACol];
  end;
end;

The grid loads correctly and the column widths are correctly adjusted to the content, but I cant modify the column width manually. What am I doing wrong that I cant modify the column width


Solution

  • You modify the column width in the OnDrawCell event. When you change the width manually, you trigger the OnDrawCell which change the width back to the content. In short, you can't do both!