Search code examples
delphidelphi-5

Dbgrid - automatic post to database


I have a form with a query, a dataset, an editable dbgrid and an updatesql component. When I need to save the changes made in the dbgrid, I call this procedure:

procedure TEditCardDetailForm.SaveChanges;
begin
  Database1.StartTransaction;
  try
    Query2.ApplyUpdates;
    Database1.Commit;
  except
    Database1.Rollback;
    raise;
  end;
  Query2.CommitUpdates;
end;

However I want the changes to be applied automatically to the database when I press Enter or go to another row after editing a cell in the dbgrid - the way it is done when I use a TTable component. Is there a way to do it?


Solution

  • You have two scenarios to handle here:

    1. save changes when changing the grid row
    2. save changes when changing the grid column

    The first one is easy to implement by calling your SaveChanges procedure in the AfterPost event of the underlying dataset (query2, a TClientDataSet?).

    For the second one you only have to call query2.Post after the column has changed. This can be done in the OnDataChange event of the datasource. Make sure to check for Field <> nil and the dataset being in insert or edit mode before calling post.