yndbtree控件
// cxg 2017-4-25
unit yndbtree;
interface
uses
SysUtils, Classes, ComCtrls, DB, Variants
;
type
PNodeRec = ^TNodeRec;
TNodeRec = record
id: string;
name: string;
pid: string;
formname: string; // formclassname
bplname: string;
end;
type
TynDBtree = class(TTreeView)
private
FDataSet: TDataSet;
FKeyID: string;
FKeyName: string;
FParentID: string;
procedure treeclick(sender: TObject);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateTree;
published
property DataSet: TDataSet read FDataSet write FDataSet;
property KeyID: string read FKeyID write FKeyID;
property KeyName: string read FKeyName write FKeyName;
property ParentID: string read FParentID write FParentID;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('yongnan', [TynDBtree]);
end;
{ TynDBtree }
constructor TynDBtree.Create(AOwner: TComponent);
begin
inherited;
Self.OnClick := treeclick;
end;
procedure TynDBtree.CreateTree;
// table struct example: id,name,pid
var
List: TStringList;
Node: TTreeNode;
Index: Integer;
PNode: PNodeRec;
begin
if not FDataSet.Active or FDataSet.IsEmpty then
Exit;
Self.Items.Clear;
List := TStringList.Create;
try
List.Sorted := True;
FDataSet.First;
while not FDataSet.Eof do
begin
PNode := new(PNodeRec);
PNode^.id := FDataSet.FieldByName(FKeyID).Text;
PNode^.name := FDataSet.FieldByName(FKeyName).Text;
PNode^.pid := FDataSet.FieldByName(FParentID).Text;
if FDataSet.FindField('formname') <> nil then
PNode.formname := FDataSet.FindField('formname').AsString;
if FDataSet.FindField('bplname') <> nil then
PNode.bplname := FDataSet.FindField('bplname').AsString;
if (FDataSet.FieldByName(FParentID).Text = '') or (FDataSet.FieldByName(FKeyID).Text = FDataSet.FieldByName(FParentID).Text) then
// add root node
Node := Self.Items.AddChild(nil, FDataSet.FieldByName(FKeyName).Text)
else
begin
// add child node
Index := List.IndexOf(FDataSet.FieldByName(FParentID).Text);
Node := Self.Items.AddChild(TTreeNode(List.Objects[Index]), FDataSet.FieldByName(FKeyName).Text);
end;
Node.Data := PNode;
List.AddObject(FDataSet.FieldByName(FKeyID).Text, Node);
FDataSet.Next;
end;
finally
List.Free;
end;
end;
destructor TynDBtree.Destroy;
var
i: Integer;
Node: TTreeNode;
begin
for i := Self.Items.Count - 1 downto 0 do
begin
Node := Self.Items[i];
Dispose(PNodeRec(Node.Data));
end;
inherited;
end;
procedure TynDBtree.treeclick(sender: TObject);
begin
if Self.Selected <> nil then
FDataSet.Locate(FKeyID, VarArrayOf([PNodeRec(Self.Selected.Data)^.id]), []);
end;
end.