Author: Mike Shkolnik
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:
1 2 procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
3 var4 i, j: Integer;
5 begin6 with yourStringGrid do7 begin8 for i := ARow to RowCount - 2 do9 for j := 0 to ColCount - 1 do10 Cells[j, i] := Cells[j, i + 1];
11 RowCount := RowCount - 1
12 end;
13 end;
2. the modificated #1:
14 15 procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
16 var17 i: Integer;
18 begin19 with yourStringGrid do20 begin21 for i := ARow to RowCount - 2 do22 Rows[i].Assign(Rows[i + 1]);
23 RowCount := RowCount - 1
24 end;
25 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.
26 type27 THackStringGrid = class(TStringGrid);
28 29 procedure DeleteRow(yourStringGrid: TStringGrid; ARow: Integer);
30 begin31 with THackStringGrid(yourStringGrid) do32 DeleteRow(ARow);
33 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.
34 if StringGrid.RowCount > 2 then35 begin36 if StringGrid.Selection.Top <> (StringGrid.RowCount - 1) then37 begin38 for iRow := StringGrid.Selection.Top to (StringGrid.RowCount - 2) do39 begin40 for iCol := 0 to (StringGrid.ColCount - 1) do41 begin42 StringGrid.Cells[iCol, iRow] := StringGrid.Cells[iCol, iRow + 1];
43 end;
44 end;
45 end;
46 StringGrid.Rows[StringGrid.RowCount - 1].Clear;
47 StringGrid.RowCount := StringGrid.RowCount - 1;