views:

63

answers:

1

New to delphi and database programming in general but am curious if there is a better way to swap records in a TDataset? I have read through some help and cant find any obvious methods. Currently I have a procedure implemented to move records down the dataset until they hit the Eof marker. However I am getting some odd errors when I get to the last record in my data. All I have is implemented a standard array-style swap routine trying to preserve data and whatnot while juggling active records.

Code So Far

procedure TForm2.btnDownClick(Sender: TObject);
var
   sTmp,sTmp2  : string;
   iTmp,iTmp2  : integer;
begin
   tblMatched.DisableControls;
   if ( tblMatched.Eof <> true ) then
   begin
      // Grab data to swap
      tblMatched.GotoBookmark( tblMatched.GetBookmark );
      iTmp := tblMatched.Fields[0].AsInteger;
      sTmp := tblMatched.Fields[1].AsString;
      tblMatched.Next;
      iTmp2 := tblMatched.Fields[0].AsInteger;
      sTmp2 := tblMatched.Fields[1].AsString;

      // Swap data
      tblMatched.Prior;
      tblMatched.Edit;
      tblMatched.Fields[0].Value := iTmp2;
      tblMatched.Fields[1].Value := sTmp2;

      tblMatched.Next;
      tblMatched.Edit;
      tblMatched.Fields[0].AsInteger := iTmp;
      tblMatched.Fields[1].AsString := sTmp;
   end;
   tblMatched.EnableControls;
end;
+2  A: 

It looks like you're using an in-memory dataset, such as TClientDataset. If you simply put an index on the dataset, it will keep things ordered for you so you don't have to rearrange them manually. Just set up the index based on whatever criteria you want to have it use.

Mason Wheeler
Yes, I am using an in memory dataset. I need to preserve the natural order of records though as it is going to be up to the user to manipulate the order of records (i.e, move record down or up).
wfoster
Not sure if this applies to all datasets, but I know that on TClientDataset you can define more than one index. Have one of them keep the natural order, and add an "order" field to the dataset that maintains the user-defined order. Put an index on that field and make it the active one when it's displaying data to the user. Then switch to the natural order index when you need to work with data in that order.
Mason Wheeler
So if I have the order field and want to decrement up (i.e, move up the dataset) then all I need to do is decrement the order field on the active record? What about the record it is taking the place of? Can I get this one before I post the decremented one?
wfoster
No, you can only have one active record at a time. You'll want to change the order value of both of the records. Try calling DisableControls on the dataset first to avoid side effects while you swap things around.
Mason Wheeler