« Lookalikes #3 | Main | Enhanced Delphi DBImage replacement (handles wmf, emf and jpg) »
September 30, 2006
Catching dataset updates in Delphi
When you navigate away from an inserted or edited record in a DataSet in Delphi, an implicit post will occur before the navigation. Sometimes, it's useful to be able to trap that and handle it in different ways. For example, you might want to ask the user if they want to save or discard the changes, or cancel the navigation and keep making changes to the current record (they might just have hit the wrong key or clicked on the wrong spot with the mouse). The bad news is that it's far from clear how to do this in the Delphi documentation. The good news is that it turns out to be pretty simple to do.
The trick lies in using a special exception called EAbort (defined along with a load of other exceptions in SysUtils). EAbort is special because it doesn't display a dialog message in the default exception handler - it's "silent". The place to do this is in the DataSet's BeforePost event handler. Throwing the EAbort simply pulls the rug from under the whole record update machinery. There's a handy procedure called Abort which will throw EAbort for you.
procedure TForm1.CDSBeforePost(DataSet: TDataSet);
begin
with DataSet as TClientDataSet do
begin
if DataSet.Modified then
begin
case MessageDlg('Save (yes) discard (no)'+
'or continue editing (cancel)?',
mtWarning,mbYesNoCancel,0) of
mrNo:
begin
Cancel;
Abort;
end;
mrCancel:
begin
Abort;
end;
end;
end;
end;
end;
There's one extra twist (not shown here) where implicit posts (generated by navigation and insert/delete events) need to be handled differently from explicit posts. This requires a boolean ExplicitPost flag that is set anytime before you call DataSet.Post from your code, and in the DBNavigator.BeforeAction event handler for the nbPost button. The flag is cleared in a transition to dsEdit or dsInsert which can be done in DataSource.OnStateChange. Then, in the DataSet.BeforePost event handler, the flag is checked and if set, the warning message is not displayed. This is not so clean, because you need to remember to set this flag before every explicit Post.
Thanks to Zarko Gajic at delphi.about.com for writing the article that put me on the right track.
Posted by daen at September 30, 2006 08:47 AM
Comments
Post a comment
Thanks for signing in, . Now you can comment. (sign out)
(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)