ccidnet????

出版日期:1999-09-06 总期号:855 本年期号:65

本期导读
要闻综合
电脑工作室
市场
硬件
软件
infotimes
结合数据浏览构件使用treeview

赖立谦

  数据浏览构件主要用于显示和编辑数据库表中的数据,因而它们又常常被称为数据控制构件。treeview构件可以显示具有树型结构的信息,它的优点在于可以增强视觉上的结构性。如何把二者的优势结合起来,使得既可以浏览到数据库表中的信息,又可以看到数据之间所具有的结构性?

  我们可以利用treenode的data属性和table的bookmark属性实现二者的结合。

  bookmark仅仅是一个指向保存有关table1光标当前位置信息的内存单元的指针。treenode的data属性实际是一个一般性的指针,它可以指向任何类型的对象。在这里我们把两个指针指向同一个内存单元。具体方法是在table1的每一条记录上都加上bookmark,并使得treenode的data指针与bookmark指针指向同一个内存单元。

  为了方便起见,这里我们就用delphi自带的数据库做示范来说明。所选数据库表是dbdemos数据库的country.db数据表。

  主要构件及属性如表1所示。

表1 数据库名: dbdemos

 

tablename:country.db
filtered:true
filter:continent=″north america″

datasource2

dataset:table1

dbedit1、dbedit2、dbedit3

datasource:datasource2

treeview1

 

  procedure tform1.formshow(sender: tobject);

  var

   j:integer;

  begin

   j := 1;

   new(continent[1]); //生成洲的结点

   continent[1]^ := ttreenode.create(treeview1.items);

   continent[1]^ := treeview1.items.addchild(continent[1]^,'north america');

   with continent[1]^ do

   begin

   imageindex := 0; // imageindex属性表示节点显示时采用的图标的序号。

   selectedindex := 0; //selectedindex属性表示节点被选中时采用的图标的序号。

   stateindex :=-1;

   end;

   table1.open; //生成国家的节点

   table1.first;

   while not table1.eof do

   begin

   new(country[j]);

   country[j]^ := ttreenode.create(treeview1.items);

  country[j]^:=

   treeview1.items.addchild(continent[1]^,table1.fieldbyname('name').asstring);

   with country[j]^ do

   begin

   imageindex := 1;

   selectedindex := 1;

   stateindex :=-1;

   data := table1.getbookmark;

   end;

   table1.next;

   end;

  end;

  此外,由于根节点(这里指的是洲节点)并没有和数据库中的记录相关联,因此当根节点被选中时应该关闭数据源,所以我们还要在treeview1的onchange事件中加入代码,具体代码如下:

  procedure tform1.treeview1change(sender: tobject; node: ttreenode);

  begin

   if node.data<>nil then

   begin

   datasource2.enabled := true;

   table1.gotobookmark(node.data)

   end

   else

   datasource2.enabled := false;

  end;

  结果如下图所示,此程序在win 95、delphi 4.0环境下运行通过。