2009. október 17., szombat

Delete the row in TStringGrid component


Problem/Question/Abstract:

How can I delete the row in TStringGrid component?

Answer:

If you worked with TStringGrid component, then you saw that in this component the Borland developers not provided the method for row deleting.
In this tip I describe the few ways for it:

1. navigate by rows and copy the row contains to the prev row:

procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
var
  i, j: Integer;
begin
  with yourStringGrid do
  begin
    for i := ARow to RowCount - 2 do
      for j := 0 to ColCount - 1 do
        Cells[j, i] := Cells[j, i + 1];
    RowCount := RowCount - 1
  end;
end;

2. the modificated #1:

procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
var
  i: Integer;
begin
  with yourStringGrid do
  begin
    for i := ARow to RowCount - 2 do
      Rows[i].Assign(Rows[i + 1]);
    RowCount := RowCount - 1
  end;
end;

3. the "hacked" way. The TCustomGrid type (the TStringGrid is TCustomGrid's successor) have the DeleteRow method. But this method allocated not in public section but in protected section. So the all successors can "see" this DeleteRow method.

type
  THackStringGrid = class(TStringGrid);

procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
begin
  with THackStringGrid(yourStringGrid) do
    DeleteRow(ARow);
end;

Personally I use the third method but the first and second are more visual.

Also you should clear the Row after moving the data to the row above.  If not you will get the old date back when you add a Row.

if StringGrid.RowCount > 2 then
begin
  if StringGrid.Selection.Top <> (StringGrid.RowCount - 1) then
  begin
    for iRow := StringGrid.Selection.Top to (StringGrid.RowCount - 2) do
    begin
      for iCol := 0 to (StringGrid.ColCount - 1) do
      begin
        StringGrid.Cells[iCol, iRow] := StringGrid.Cells[iCol, iRow + 1];
      end;
    end;
  end;
  StringGrid.Rows[StringGrid.RowCount - 1].Clear;
  StringGrid.RowCount := StringGrid.RowCount - 1;

Nincsenek megjegyzések:

Megjegyzés küldése