Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emptying string grid in Delphi

In Delphi, is there a fast way of emptying a TStringgrid (containing in excess of 5000 rows) that will also free the memory?

Setting the rowcount to 1, empties the grid but does not free the memory.

Thanks in advance,

Paul

like image 241
Paul Jones Avatar asked Nov 11 '11 15:11

Paul Jones


2 Answers

This should uninitialize the allocated strings (from the string list where the row texts are stored). Cleaning is done by columns since you have a lot of rows.

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to StringGrid1.ColCount - 1 do
    StringGrid1.Cols[I].Clear;
  StringGrid1.RowCount := 1;
end;
like image 186
TLama Avatar answered Oct 20 '22 00:10

TLama


By "does not free the memory", do you mean that if you set RowCount := 1, and then set the RowCount := 10' you can still see the old content of theCells`?

If so, this is an old issue and has nothing to do with the memory not being freed; it's simply because you just happen to see the previous content of the memory when it's allocated again, because memory isn't zero'd out.

I have a pretty standard routine in a utility unit that deals with this visual glitch, and unless the grid is huge works fast enough. Just pass the TStringGrid before you change the RowCount or ColCount to a lower value.

procedure ClearStringGrid(const Grid: TStringGrid);
var
  c, r: Integer;
begin
  for c := 0 to Pred(Grid.ColCount) do
    for r := 0 to Pred(Grid.RowCount) do
      Grid.Cells[c, r] := '';
end;

Use it like this:

ClearStringGrid(StringGrid1);
StringGrid1.RowCount := 1;
like image 21
Ken White Avatar answered Oct 19 '22 23:10

Ken White