表结构及记录
object tarea: TFDQuery
Connection = FDConnection1
SQL.Strings = (
'select *'
'from tArea order by fParentCode')
Left = 160
Top = 240
end
object tv: TTreeView
Left = 0
Top = 0
Width = 554
Height = 320
Align = alClient
Indent = 19
TabOrder = 1
ExplicitLeft = 40
ExplicitTop = 32
ExplicitWidth = 121
ExplicitHeight = 97
end
代码
procedure TForm1.FormCreate(Sender: TObject);
var
nodes:ttreenodes;
node:ttreenode ;
CurItem ,CurItem1:Ttreenode ;
nodestr:string;
lastparent,temp:string;
i,j:integer ;
begin
TV.Items.Clear;
nodes:=TV.Items;
Tarea.Active:=true;
node:=nodes.add(nil,Tarea.FieldByName('fCode').Value+'_'+Tarea.FieldByName('fNAME').Value);
Tarea.Next;
while NOT Tarea.Eof do
BEGIN
if Tarea.FieldByName('fParentCode').AsString='' then
nodes.add(nil,Tarea.FieldByName('fCode').Value+'_'+Tarea.FieldByName('fNAME').Value); //省份
if Tarea.FieldByName('fParentCode').AsString<>lastparent then
//当前记录 fParentCode跟上条记录 fParentCode 不相等,表明是换一个父代了
//需查找
begin
CurItem := TV.Items.GetFirstNode;
while CurItem <> nil do
begin
if copy( CurItem.Text,1,pos('_',CurItem.Text)-1) =Tarea.FieldByName('fParentCode').Value then
begin
CurItem.Selected:=true;
break;
end;
CurItem := CurItem.GetNext;
end;
nodes.addCHILD(CurItem,Tarea.FieldByName('fCode').Value+'_'+Tarea.FieldByName('fNAME').Value); //
end;
if (Tarea.FieldByName('fParentCode').AsString<>'')
AND
(Tarea.FieldByName('fParentCode').AsString=lastparent)
//当前记录 fParentCode跟上条记录 fParentCode 相等,表明是同一个父代了,直接添加就行
then
BEGIN
nodes.addCHILD(CurItem,Tarea.FieldByName('fCode').Value+'_'+Tarea.FieldByName('fNAME').Value); //
END;
lastparent:= Tarea.FieldByName('fParentCode').AsString;
Tarea.Next;
END;
nodes.GetFirstNode;
end;
end.
效果如下
-------------------------------
另可以用 \DevExpress VCL_18.2.5 (网上有下载) +TdxDBTreeView +delphi 10.3
设置如下:
object Form5: TForm5
Left = 0
Top = 0
Caption = 'Form5'
ClientHeight = 300
ClientWidth = 635
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object dxDBTreeView1: TdxDBTreeView
Left = 24
Top = 40
Width = 201
Height = 228
ShowNodeHint = True
DataSource = DataSource1
KeyField = 'fCode'
ListField = 'fName'
ParentField = 'fParentCode'
RootValue = Null
SeparatedSt = ' - '
RaiseOnError = True
Indent = 19
ParentColor = False
Options = [trDBCanDelete, trDBConfirmDelete, trCanDBNavigate, trSmartRecordCopy, trCheckHasChildren]
SelectedIndex = -1
TabOrder = 0
end
object DBNavigator1: TDBNavigator
Left = 0
Top = 0
Width = 635
Height = 25
DataSource = DataSource1
Align = alTop
TabOrder = 1
end
object ClothuConnection: TFDConnection
Params.Strings = (
'ConnectionDef=ClothU')
Connected = True
LoginPrompt = False
Left = 383
Top = 87
end
object TareaTable: TFDQuery
Active = True
Connection = ClothuConnection
SQL.Strings = (
'SELECT * FROM ClothU.dbo.tArea')
Left = 383
Top = 135
end
object DataSource1: TDataSource
DataSet = TareaTable
Left = 312
Top = 152
end
end