您可以将数据集的所有记录转换为 TStringList 并对其进行排序。
在接口部分声明这个:
TForm1=class(...)
RecordList:TStringList;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
end;
TCategoryItem=class
public:
CategoryTitle:string;
Id,ParentId:Variant;
end;
在实施部分:
constructor TForm1.Create(AOwner: TComponent);
begin
inherited ;
RecordList:=TstringList.create(true); // use this code in FormCreate also
end;
destructor TForm1.Destroy;
begin
...
RecordList.Free;// use this code in FormDestory also
end;
procedure TForm1.AdoQuery1AfterOpen(DataSet:TDataSet);
var
Item,RootItem:TCategoryItem;
begin
DataSet.First;
DataSet.DisableControls;
try
(*add abstract root item to RecordList if needed
RootItem:=TCategoryItem.Create;
RootItem.CategoryTitle:='ROOT';
RecordList.AddObject('',RootItem);*)
while not DataSet.Eof do
begin
Item:=TCategoryItem.Create;
Item.CategoryTitle:=DataSet['Cateogory'];
Item.Id:=DataSet['CodeCategory'];
Item.ParentId:=DataSet['ParentCategory'];
RecordList.AddObject(VarToStr(Item.Id),Item);
DataSet.Next;
end;
finally
RecordList.Sort; // for use find(binary search)
DataSet.EnableControls;
DataSet.First;
end;
end;
procedure TForm1.OnGetFieldText(Sender: TField; var Text: string;
DisplayText: Boolean);
var
Idx:Integer;
ParentValue:Variant;
Item:TCategoryItem;
Texts:TStringList;
begin
ParentValue:=Sender.Value;
Texts:=TStringList.create;
try
while RecordList.Find(varToStr(ParentValue),Idx) do
begin
Item:=RecordList.Objects[Idx] as TCategoryItem;
Texts.Insert(0,Item.CategoryTitle);
ParentValue:=Item.ParentId;
end;
Texts.Delimiter:='>';
Text:=Texts.DelimitedText;
finally
Texts.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ADOQuery1.FieldByName('parentcategory').OnGetText := OnGetFieldText;
ADOQuery1.Refresh;
end;