Check if row was changed in a TClientDataset
Asked Answered
L

2

6

I have a TClientDataset with n fields and I have to loop through them to count how many have changed but doing:

if (Cds.fields1.Value <> Cds.fields1.OldValue) and (Cds.fields2.Value <> Cds.fields2.OldValue) etc....

or looping through Cds.fields[I] is not very 'clean'

Is there a Cds.RowChanged method or something?

Loaves answered 8/7, 2016 at 14:36 Comment(0)
T
13

You can use the TClientDataSet's UpdateStatus property for this:

if Cds.UpdateStatus = usModified then
  //  current row was changed

Other possible values are usUnmodified, usInserted and usDeleted. Unlike the TDataSet.Modified property, the UpdateStatus for the current row persists after its change(s) have been posted back to the CDS by CDS.Post. Obviously, it's up to you which of these number values you need for your application.

As noted in the Online Help, you can use the UpdateStatus to set the value of a calculated field:

procedure TForm1.ClientDataSet1CalcFields(DataSet: TDataSet);
begin
  case TClientDataSet(DataSet).UpdateStatus of
    usUnmodified: FieldByName('Status').AsString := '';
    usModified: FieldByName('Status').AsString := 'M';
    usInserted: FieldByName('Status').AsString := 'I';
    usDeleted: FieldByName('Status').AsString := 'D';
  end;
end;

You can also use its StatusFilter property to temporarily filter a TClientDataSet to select rows with a specfic UpdateStatus:

procedure TCDSForm.Button1Click(Sender: TObject);
begin
  if CDS.StatusFilter = [] then
    CDS.StatusFilter := [usModified]
  else
    CDS.StatusFilter := [];
  Caption := IntToStr(CDS.RecordCount);
end;

Note that CDS.RecordCount with the StatusFilter set to usModified does not necessarily return the same value as the CDS.ChangeCount property, because the ChangeCount value includes the number of rows inserted as well as the number that have been modified.

Tomlinson answered 8/7, 2016 at 14:51 Comment(3)
Note that Cds.fields1.Value <> Cds.fields1.OldValue will include inserted records as well. That code is from the question.Analemma
@SertacAkyuz: I haven't tested that, but if you say so, good point.Tomlinson
Actually I didn't test too, I assume OldValue to be null for an inserted record.Analemma
A
2

You don't have to loop through the dataset, you can use the ChangeCount property.

Analemma answered 8/7, 2016 at 19:5 Comment(2)
That gives me the overall changes, not row specific.Loaves
I was misled by your question then. ".. I have to loop through them to count how many have changed .." led me to think your goal was to have a count.Analemma

© 2022 - 2024 — McMap. All rights reserved.