I am programming in pascal and I use Delphi Xe7. I am trying to make the width of the columns of a grid adjust to its content, but to allow the width to be modified to suit the user. The grid is one TStringAlignGrid
and this is the code I use to adjust it to the content:
procedure TfPlanillaOrdenPreparacion.gDetalleDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
vWidth : Integer;
begin
if (FormPosition.WMaximized = True) then
begin
vWidth := gDetalle.Canvas.TextWidth(gDetalle.Cells[ACol, ARow]);
if vWidth > aColWidthExpanded[ACol] then
aColWidthExpanded[ACol] := vWidth+20;
gDetalle.ColWidths[ACol] := aColWidthExpanded[ACol];
end;
end;
At the time of loading the data, it is loaded correctly in the grid and adjusts to the content as it should be, but when you want to enlarge or reduce a column, I cannot do it. It's like I know that it disables the property that lets me modify the width. I don't understand what I'm doing wrong, I'm pretty new to delphi xe7, I appreciate your help :D.
The behavior you describe makes sense, since you're resizing the cell in the event
DrawCell
, which is executed every time the cell is drawn (not just before the user resizes, but after as well).What is usually done in situations like this is to have a separate method to adjust the width of the column only when it is necessary, for example, after loading information in the grid.
The method to automatically adjust the width of the column can be similar to this:
Which you then call when convenient, for example the following code would call the method to wrap all the columns after loading data from a text file:
This way, since you no longer programmatically touch the width of the columns later, the user will have the freedom to make them smaller or larger to their liking. You can also add a way for the user to refit the column to the width of the content, for example by double-clicking on a column title, you call the method again
AdjustColumnWidthBestFit
and that's it.