开发者

How to update a TClientDataSet with changes made to the DB without it knowing?

开发者 https://www.devze.com 2023-04-07 05:08 出处:网络
I have a simple TClientDataSet component that I use to populate some data-aware co开发者_StackOverflowmponents. However, if I insert data into my database using this dataset, I can\'t seem to find a p

I have a simple TClientDataSet component that I use to populate some data-aware co开发者_StackOverflowmponents. However, if I insert data into my database using this dataset, I can't seem to find a proper way to sync it back into my TClientDataSet component.

How do I achieve this?


The TClientDataSet component has a Refresh method that does exactly that. Took some time for me to find this out in the docs, though. :)

From the docs:

From DB.pas

procedure Refresh;

Re-fetches data from the database to update a dataset's view of data.

Call Refresh to ensure that an application has the latest data from a database. For example, when an application turns off filtering for a dataset, it should immediately call Refresh to display all records in the dataset, not just those that used to meet the filter condition.

Note: The Refresh method does not work for all TDataSet descendants. In particular, TQuery components do not support the Refresh method if the query is not "live". To refresh a static TQuery, close and reopen the dataset. TDataSet generates a BeforeRefresh event before refreshing the records and an AfterRefresh event afterwards.

Note: Most datasets try to maintain the current record position when you call refresh. However, this is not always possible. For example, the current record may have been deleted from the server by another user. Unidirectional datasets have no mechanism for locating the current record after a refresh, and always move back to the first record.

Warning: Unidirectional datasets refresh the data by closing and reopening the cursor. This can have unintended side effects if, for example, you have code in the BeforeClose, AfterClose, BeforeOpen, or AfterOpen event handlers.


Closing and opening the CDS didn't work for me. I'm using Delphi XE2, Update 3, with ADO tables connecting to an Access 2007 database. The only way I could refresh the data in my CDS was this:

procedure TForm1.PeopleRefreshButtonClick(Sender: TObject);
// this actually re-loads the data from the table!
begin
  DM1.PeopleTable.Close;
  DM1.PeopleTable.Open;
  DM1.PeopleCDS.Refresh;
end;

A refresh button on the form closes, then opens the table. Then I refresh the ClientDataSet.


Basically, you must close the TClientDataset and then open it, loading the data from the database the same way you did originally. If the TClientDataset is connected to a TDataSetProvider, which is connected to a TDataset/TQuery descendant, all you have to do is close TClientDataset then open it.

0

精彩评论

暂无评论...
验证码 换一张
取 消