Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a TStringGrid row?

I have a TStringGrid, and I want to delete the selected row. Basic things I've tried only delete the last row. How do I delete an arbitrary row?

like image 582
CrazyGirl Avatar asked May 03 '13 03:05

CrazyGirl


1 Answers

If the code you've tried only deletes the last row, then you're probably just decrementing the RowCount property. That indeed always makes its modifications on the end of the list of rows. With that in mind, you could write code to ensure that the row you no longer want is the one at the end, and then delete the last row. (The most direct way would be to move the row, and there's a MoveRow method, but it's protected. If you wish to call protected methods, though, you may as well just call DeleteRow instead.)

Using only public and published members, it's possible to write a loop that deletes an arbitrary row. For example, here's some code inspired by Scalabium Software's FAQ on this topic:

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

It copies the contents of each row below the one you wish to delete into the row above. At the end of the loop, the row you wish to delete has been overwritten (by the row immediately below it) and there are two copies of the final row. Then it simply deletes the final row.

To delete the current row of the grid, call the function like this:

DeleteRow(Grid, Grid.Row);
like image 105
Rob Kennedy Avatar answered Sep 28 '22 06:09

Rob Kennedy