Delphi 2006 TClientDataSet index issue
I use a ClientDataSet
with a DataSetProvider
linked to a local DataSet.
When I want to edit the data in the DataSet I open the ClientDataSet and add some indexes to it. After I'm done editing the data I close the ClientDataSet.
All works fine, except that when I open the ClientDataSet again and I select an index it's throwing an exception with the message "index 'xxx' not found".
What I'm doing wrong?
Here is the code for opening the ClientDataSet:
Application.CreateForm (TfrmCardDep, frmCardDep);
try
with DM.tblCCardDep do
begin
IndexDefs.Clear;
if not Active then Open;
AddIndex ('iDepID', 'DepID', []);
AddIndex ('iDep', 'Dep', []);
IndexName := 'iDep';
FieldByName('Dep').DisplayLabel := 'Departament';
FieldByName('Dep').DisplayWidth := 50;
FieldByName('DepID').Visible := false;
end;
frmCardDep.ShowMod开发者_如何学编程al;
finally
if DM.tblCCardDep.Active then DM.tblCCardDep.Close;
frmCardDep.Free; frmCardDep := nil;
end;
DM.tblCCardDep is the ClientDataset
After the first round you have IndexName
set on the ClientDataSet
. When IndexDefs
are discarded the index it refers becomes invalid. Clear IndexName
before re-opening the dataset, i.e. modify your code to read:
[..]
try
with DM.tblCCardDep do
begin
IndexDefs.Clear;
IndexName := ''; // <- here
if not Active then Open;
[..]
Or use something like this: [..]
try
with DM.tblCCardDep do
begin
if not Active then Open;
if IndexDefs.Count = 0 then
begin
AddIndex ('iDepID', 'DepID', []);
AddIndex ('iDep', 'Dep', []);
IndexDefs.Update; // Update IndexDefs
IndexName := 'iDep';
end;
FieldByName('Dep').DisplayLabel := 'Departament';
[..]
Client dataset indexes are always discarded when you close the client dataset. "Persistent index" in the context of the client dataset means that it stays in memory as long as the client dataset is open:
Understanding ClientDataSet Indexes
TClientDataset indexes: temporary or persistent?
精彩评论