Delete or clear rows in a TStringGrid #191

If you ever needed to delete rows from a TStringGrid component you should have noticed that it does not have a method for deleting or clearing rows. Here is nice class helper which does that.

Declare a class helper type:

type
  TStringGridRowDeletion = class helper for TStringGrid
  public
    procedure RemoveRows(RowIndex, RCount: Integer);
    procedure Clear;
  end;

and implement it as follows:

{ TStringGridRowDeletion }
 
procedure TStringGridRowDeletion.Clear;
var
  i: integer;
begin
  for i := 0 to RowCount -1 do
    RemoveRows(0, RowCount);
end;
 
procedure TStringGridRowDeletion.RemoveRows(RowIndex, RCount: Integer);
var
  i: Integer;
begin
  for i := RowIndex to RowCount - 1 do
    Rows[i] := Rows[i + RCount];
  RowCount := RowCount -RCount;
end;

Now all you have to do is to add this helper in a unit where you need to call RemoveRows or create a separate unit for it and "use" it where required. From now on you can delete rows the easy way. E.g.

var
  myStringGrid: TStringGrid;
begin
  ...
  myStringGrid.RemoveRows(0, 4);
  ...
end;

Note: the RemoveRows method can be invoked from all TStringGrid descendants.

Author: Dorin Duminica
Contributor: Riccardo Faiella (Topellina)
Added: 2012/07/06
Last updated: 2012/07/06