Chris1701 0 Posted December 11 I have a form with a TStringgrid that I'd like to be able to programmatically set the column widths based on the text lengths in the grid itself. I used Google to search and didn't find a whole lot but I did find someone who provided this: Procedure TEditSeriesForm.SetColumnFullWidth( Var Grid: TStringGrid; ACol: Integer); var I, Str_Width, Col_Width: Integer; begin { set the width of the defined column in a string grid to the width of the widest string } Str_Width:=0; Col_Width:=0; For i := 0 To Grid.RowCount - 1 do begin // get the pixel width of the complete string Col_Width := EditSeriesForm.Canvas.TextWidth(Grid.Cells[Acol,i]); // if its greater, then put it in str_width If col_width>str_width then str_width:=col_width; end; Grid.ColWidths[Acol] := col_width+5; // +5 for margins. adjust if neccesary End; The problem is that this line of code "Col_Width := EditSeriesForm.Canvas.TextWidth(Grid.Cells[Acol,i]);" generates an exception class $C0000005 with message 'C0000005 ACCESS_VIOLATION" so I have no idea why this doesn't work so does anyone know offhand what's wrong with this or have an alternate method for checking and setting the string grid column widths based on the length of the text values in each column? Share this post Link to post
Remy Lebeau 1429 Posted December 12 2 hours ago, Chris1701 said: The problem is that this line of code "Col_Width := EditSeriesForm.Canvas.TextWidth(Grid.Cells[Acol,i]);" generates an exception class $C0000005 with message 'C0000005 ACCESS_VIOLATION" so I have no idea why this doesn't work so does anyone know offhand what's wrong with this Did you try debugging the code? Probably the global EditSeriesForm variable is nil. Since the code is inside of a method of the Form class, it should be using the method's own Self pointer instead of using the global Form pointer: Col_Width := Self.Canvas.TextWidth(Grid.Cells[Acol,i]); But, the code really should be using the StringGrid's Canvas instead of the Form's Canvas: Col_Width := Grid.Canvas.TextWidth(Grid.Cells[Acol,i]); Also, there is no reason for the Grid parameter to be marked as var, since the code is not changing which object the variable points at. Objects are passed around by pointer, and passing that pointer into the method by value instead of by var reference will work just fine in this situation. Share this post Link to post
Chris1701 0 Posted December 12 Thanks Remy, I found this code on an old StackOverflow thread so I didn't write it and was just trying to make it work. The change you suggested worked like a charm, thanks so much! Merry Christmas! Share this post Link to post