1
votes

I have a StringGrid in my form and when I press the Button1, I move some cells inside this grid. Here's an example:

enter image description here

When I press the Button1, I go from the situation A to the situation B. But I'd like to be able to do the reverse thing too: I mean that I'd like to go from B to A when I press another button called Button2.

I'd like to create something like an "undo" button. How could I do this? I am using Lazarus.

I need to do only 1 undo. Here's the procedure that moves the StringGrid's cells:

procedure TForm1.SortGrid(Grid : TStringGrid; const SortCol:integer; const datatype:integer; const ascending:boolean);

var
   i : integer;
   tempgrid:tstringGrid;
   list:array of integer;
begin
  tempgrid:=TStringgrid.create(self);

  with tempgrid do
  begin
    rowcount:=grid.rowcount;
    colcount:=grid.colcount;
    fixedrows:=grid.fixedrows;
  end;

  with Grid do
  begin
    setlength(list,rowcount-fixedrows);
    for i:= fixedrows to rowcount-1 do
    begin
      list[i-fixedrows]:=i;
      tempgrid.rows[i].assign(grid.rows[i]);
    end;

    //Call the procedure and sort the stuff 
    Quicksort(Grid, list,0,rowcount-fixedrows-1,sortcol,datatype, ascending);

    for i:=0 to rowcount-fixedrows-1 do
    begin
      rows[i+fixedrows].assign(tempgrid.rows[list[i]])
    end;
    row:=fixedrows;
  end;

  tempgrid.free;
  setlength(list,0);
  screen.cursor:=crdefault;

end; 

And when I click the Button1...

SortGrid(StringGrid1,1,1,true);
1
How many times do you expect a user to undo? This is usually done by saving a list in the background of every little change that happens. Without seeing your code, it's impossible for us to know how to advise you further than that. - Jerry Dodge
You'd clearly have to track whatever action you took when you pressed Button1, and reverse it in order to undo. It's impossible to tell you how to do that, because you didn't show us your code that handles the movement in the first place. How do you "go from situation A to the situation B"? - Ken White
I need only 1 undo. I was thinking to save the StringGrid A, then change the cells positions (StringGrid B). Then, if the user wants to come back to A, load the saved StringGird (which is the A). - Alberto Rossi
Creating a new third grid is definitely overkill. Just store the values in variables. This is extremely easy, not sure where the trouble is. - Jerry Dodge
I thought that too, don't worry. But since I am learning Delphi I didn't know if there were other "faster" solutions :) - Alberto Rossi

1 Answers

4
votes

You can use the Cols property to save and restore the contents of that column:

var
  MySavedData: TStringList;
begin
  ...
  MySavedData := TStringList.Create;
  // Save the contents of the column 1
  MySavedData.Assign(StringGrid1.Cols[1]);
  SortGrid(StringGrid1,1,1,true);
  // Restore the contents of the column 1
  StringGrid1.Cols[1] := MySavedData;
  ...
end;

Obviously MySavedData should be freed at some point.