一种较简易的树型控件节点构造法

把数据库中的数据在树型控件(TreeView)中正确显示是较为不易,我在实际编程中经常为之头痛,也使用了不少方法,后来仔细研究了cxDBTreeList控件,受到启发解决了问题:
1、 创建一个表,为简化程序,只创建三个数据字段,定义如下:
字段名 类型 长度 说明
Mytext nvarchar 50 要显示的文字
MyID int 4 主关键ID,(可使用自动编号)
MYParentID int 4 记录父主关键ID,无父节点是时为0
2、窗体中放置一个TreeView控件;
2、使用数据控件连接该数据表(本例中使用ADOTable);
3、声明一个过程:

procedure MyNode(MyParentID:string;MyNodeT:TTreeNode);

 4、过程代码:

procedure TA_FinanceSubjec.MyNode(MyParentID: string;MyNodeT:TTreeNode);
type
  PMyList = ^AList;
    AList = record
    MyParendID: string;
    MyNodeP: TTreeNode ;
  end;
var
  ATempList: TList;
  I: Integer;
  ARecord:PMyList;
  s:string;
  node:TTreeNode;
begin
   ADOTable1.Filtered:=true;
   ADOTable1.Filter:=' MYParentID ='+MyParentID;
   if ADOTable1.RecordCount<1 then exit;
   ATempList := TList.Create;
   try
    ADOTable1.First;
    while not ADOTable1.Eof  do
    begin
       New(ARecord);
       s:='('+ADOTable1MyID.AsString +')'+ ADOTable1Mytext.AsString  ;
       node:= TreeView1.Items.AddChild(MyNodeT   ,s) ;
       ARecord^.MyParendID:= ADOTable1Mytext.AsString  ;
       Arecord^.MyNodeP  :=node;
       ATempList.Add(Arecord);
       ADOTable1.Next;
      end;
     for I :=0 to ATempList.Count - 1 do
     begin
       Arecord:=ATempList.Items[i];
       MyNode(Arecord^.MyParendID,Arecord^.MyNodeP );
       end;
   finally
    for I := 0 to ATempList.Count - 1 do
      Dispose(ATempList[I]);
    ATempList.Free;
    ADOTable1.Filtered:=false;
  end;
end;

procedure TForm1.FormShow(Sender: TObject);
begin
 ADOTable1.DisableControls;
 if ADOTable1.Active then
     ADOTable1.Active:=false;
     ADOTable1.Active:=true;
     ADOTable1.First;
     MyNode('0',nil  );
  ADOTable1.EnableControls;     
end;

 

5、改变节点位置时(在OnDragDrop中实现):

var iPos1:integer;s:string;
begin
  ipos1:= pos(')', TreeView1.Selected.Parent);
 if ipos1>1 then
   begin
  s:=copy(RzTreeView1.Selected.Text,2,iPos-2);
  ADOTable1.Locate('MyID',s,[loPartialKey]);
ADOTable1.edit;
   ADOTable1MYParentID.asinteger:=
    StrToInt(copy(TreeView1.Selected.Parent,2, ipos1-2)) ;
ADOTable1.post;
  End;

 

(出处:DelphiFans.com)

阅读更多
文章标签: 编程
个人分类: delphi
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭