2
while not TBLOrder.Eof do
begin
  TBLOrder.Locate('OrderID', Total, []);
  TBLOrder.Delete;
end;

This just deletes every single row in my Access Database, which is really annoying.

I'm trying to get the program to delete the selected row (which is Total).

From what I understand, It should locate the selected row, which is equal to Total. e.g. If Total = 3 it should find the row where OrderID = 3 and then delete that row.

Any help is appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Craig
  • 675
  • 1
  • 7
  • 23

2 Answers2

3

Try this instead (Max's routine requires you to loop through the entire dataset, which is fine unless it's got many rows in it):

while (TblOrder.Locate('OrderID', Total, [])) do
  TblOrder.Delete;

TDataSet.Locate returns a Boolean; if it's True, the found record is made the active record and you can then delete it. If it returns False (meaning the record is not found), the call to Delete is never made.

BTW, the problem with your original code is that you test for Eof, but never check to see if the Locate finds the record; you just delete whatever record you're on, and then test for Eof again. If you're not at Eof, you call Locate, ignore whether or not it found the record, and delete whatever row you're on. This then repeats over and over again until there are no more records, at which point Eof returns true and you break the loop.

Ken White
  • 123,280
  • 14
  • 225
  • 444
2

If there is just one row that contains an ORDERID equal to 3, you don't need the WHILE loop.

If you expect more than one row with an ORDERID equal to 3, do this:

TBLOrder.first; // you could also do the locate here if it's a big table
while not TBLOrder.Eof do
begin
 if TBLOrder.FieldByName('OrderID').AsInteger = 3 then
   TBLOrder.delete
 else
   TBLOrder.next;
 end;

Otherwise, you could also use SQL.

Max Williams
  • 821
  • 1
  • 7
  • 13