vb TreeView 控件应用实例
- 格式:doc
- 大小:42.00 KB
- 文档页数:7
VB TreeView控件使用详解(2012-06-16 15:08:16)转载▼分类:VB编程笔记标签:it第一小时:学习直接用代码将数据填充到树控件中。
为什么要先学习直接用代码将数据填充到树控件中?因为这种方法是最简单的,代码也最容易理解,学习树控件,先将这个学会,已经掌握了一半,所以先不要急着想怎么将表中的数据填充到树控件中,在第一小时里,树控件和表完全没有关系。
目的:我们要在树控件中建立如下的一个3层级关系水果||__苹果| |__红富士| |__国光||__葡萄|__红提子|__青提子解释:水果包含2种,一种是苹果,一种是葡萄,苹果又包含2种,一种是红富士,一种是国光,葡萄也如此。
在这里:“爷”是水果,“父”是苹果,葡萄,“子”是红富士,国光,红提子,青提子。
概括如下:爷(只能有一个):水果父(这里有2个):父1:苹果;父2:葡萄子(这里有4个):子1:红富士(父1苹果的子);子2:国光(父1苹果的子);子3:红提子(父2葡萄的子);子4:青提子(父2葡萄的子)1、新建一个窗体,在窗体上放置两个控件,一个是Treeview,一个是Imagelist如何找到这两个控件?Treeview控件在“工具箱”的榔头加扳手图标(其他控件)中选“Microsoft Treeview Control,Version 6.0"Imagelist控件在“工具箱”的榔头加扳手图标(其他控件)中选“Microsoft Imagelist Control,Version 6.0"Treeview控件大家都明白干什么用的,Imagelist控件是干什么用呢?原来这个控件是放图标用的,如果你想在树控件中显示图标的,这个图标都将储存在ImageList控件中。
2、设置这两个控件的属性首先要讲清楚控件的属性设置有2种,一种是设置这个控件在ACCESS中的属性,比如名称等。
一种是设置这个控件本身的属性。
VBtreeview使用示例代码(从数据库中读入)_天之蓝数据库连接参数设置'*****定义数据库连接参数Dim rs As New ADODB.ConnectionDim bs As New ADODB.RecordsetDim sql As String '查询字符串Dim filename As String '数据库名称Dim ctrFi '连接字符串Dim nodX As Node '树形控件节点类型定义连接并打开数据库:'******连接并打开数据库**********Public Sub connectdata()filename = App.Path + "\" + "123.mdb"ctrFi = "Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=" & filenamers.Open ctrFiEnd Sub数据库中表与字段设置:数据库名称:123.mdb表一:名称:usere字段:user(字符型),type(字符型)表二:名称:typer字段:usertype(字符型)窗口上加入一个Imagelist控件,加入3个图标,再加入一个treeview控件,treeview控件图标属性与imagelis关联(即在treeview 控件上点右键,选择图像列表里的imagelist1,必须先添加imagelist1控件才有显示)添加节点代码:TreeView1.LineStyle = tvwRootLinesCall connectdatasql = "select * from typer" '添加根节点bs.Open sql, rs, 1If bs.RecordCount <> 0 Thenbs.MoveFirstDo While bs.EOF = FalseSet nodX = TreeView1.Nodes.Add(, , bs.Fields("usertype").Value, bs.Fields("usertype").Value, 3) bs.MoveNextLoopEnd Ifbs.Closers.Close'***添加子节点***Call connectdatasql = "select * from usere"bs.Open sql, rs, 1If bs.RecordCount <> 0 Thenbs.MoveFirstDo While bs.EOF = FalseSet nodX = TreeView1.Nodes.Add(bs.Fields("type").Value, tvwChild, bs.Fields("user").Value, bs.Fields("user").Value, 2) bs.MoveNextLoopEnd Ifbs.Closers.Close。
VB TreeView控件使用详解(2012-06-16 15:08:16)标签:分类:第一小时:学习直接用代码将数据填充到树控件中。
为什么要先学习直接用代码将数据填充到树控件中因为这种方法是最简单的,代码也最容易理解,学习树控件,先将这个学会,已经掌握了一半,所以先不要急着想怎么将表中的数据填充到树控件中,在第一小时里,树控件和表完全没有关系。
目的:我们要在树控件中建立如下的一个3层级关系水果||__苹果| |__红富士| |__国光||__葡萄|__红提子|__青提子解释:水果包含2种,一种是苹果,一种是葡萄,苹果又包含2种,一种是红富士,一种是国光,葡萄也如此。
在这里:“爷”是水果,“父”是苹果,葡萄,“子”是红富士,国光,红提子,青提子。
概括如下:爷(只能有一个):水果父(这里有2个):父1:苹果;父2:葡萄子(这里有4个):子1:红富士(父1苹果的子);子2:国光(父1苹果的子);子3:红提子(父2葡萄的子);子4:青提子(父2葡萄的子)1、新建一个窗体,在窗体上放置两个控件,一个是Treeview,一个是Imagelist如何找到这两个控件Treeview控件在“工具箱”的榔头加扳手图标(其他控件)中选“Microsoft Treeview Control,Version "Imagelist控件在“工具箱”的榔头加扳手图标(其他控件)中选“Microsoft Imagelist Control,Version "Treeview控件大家都明白干什么用的,Imagelist控件是干什么用呢原来这个控件是放图标用的,如果你想在树控件中显示图标的,这个图标都将储存在ImageList控件中。
2、设置这两个控件的属性首先要讲清楚控件的属性设置有2种,一种是设置这个控件在ACCESS中的属性,比如名称等。
一种是设置这个控件本身的属性。
要设置这个控件在ACCESS中的属性,选中控件后按鼠标右键选“属性”就可以了。
duilib treeview 用法总结下载温馨提示:该文档是我店铺精心编制而成,希望大家下载以后,能够帮助大家解决实际的问题。
文档下载后可定制随意修改,请根据实际需要进行相应的调整和使用,谢谢!并且,本店铺为大家提供各种各样类型的实用资料,如教育随笔、日记赏析、句子摘抄、古诗大全、经典美文、话题作文、工作总结、词语解析、文案摘录、其他资料等等,如想了解不同资料格式和写法,敬请关注!Download tips: This document is carefully compiled by the editor. I hope that after you download them, they can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you!In addition, our shop provides you with various types of practical materials, such as educational essays, diary appreciation, sentence excerpts, ancient poems, classic articles, topic composition, work summary, word parsing, copy excerpts, other materials and so on, want to know different data formats and writing methods, please pay attention!当今社会,随着信息化的发展,人们对于数据的展示和管理需求日益增加。
VB 6.0 treeview运用技术一览Option ExplicitDim I As IntegerDim J As IntegerDim nodx As NodeDim CunZai As Boolean '定义变量Private Sub Command1_Click()If Txt(0).Text <> "" And Txt(1).Text <> "" Then '不允许建立零字节的父节点和子节点CunZai = FalseJ = TreeView1.Nodes.CountFor I = 1 To TreeView1.Nodes.Count '检查新输入的父节点名称是否存在If TreeView1.SelectedItem.Children > 0 ThenIf Txt(0).Text = TreeView1.Nodes(I).Text Then CunZai = TrueEnd IfNext IIf CunZai = True Then '若存在, 则在父节点下建立子节点Set nodx = TreeView1.Nodes.Add(Txt(0).Text, tvwChild, "child" & J,Txt(1).Text, 3)Else ,若不存在,则建立父节点和子节点Set nodx = TreeView1.Nodes.Add(, , Txt(0).Text, Txt(0).Text, 1)Set nodx = TreeView1.Nodes.Add(Txt(0).Text, tvwChild, "child" & J,_Txt(1).Text, 3)End IfTreeView1.RefreshElseIf Txt(0).Text = "" Then MsgBox "请输入父节点名称!", vbInformation, "警告!"'系统提示ElseIf Txt(1).Text = "" Then MsgBox "请输入子节点名称!", vbInformation, "警告!"End IfEnd SubPrivate Sub Command2_Click()For I = 1 To TreeView1.Nodes.CountTreeView1.Nodes(I).Expanded = True '展开所有节点Next IEnd SubPrivate Sub Command3_Click()For I = 1 To TreeView1.Nodes.CountTreeView1.Nodes(I).Expanded = False '收起所有节点Next IEnd SubPrivate Sub Command4_Click()TreeView1.Sorted = True '排列顺序End SubPrivate Sub Command5_Click()If TreeView1.SelectedItem.Index <> 1 ThenTreeView1.Nodes.Remove TreeView1.SelectedItem.Index '删除选定的节点End IfEnd SubPrivate Sub Command6_Click()End '退出程序End SubPrivate Sub Form_Load()TreeView1.LineStyle =TvwTreeLines '在兄弟节点和父节点之间显示线TreeView1.ImageList = ImageList1 '链接图像列TreeView1.Style = tvwTreelinesPlusMinusPictureText'树状外观包含全部元素Set nodx = TreeView1.Nodes.Add(, , "蒲子明", "蒲子明", 1)'建立名称为"蒲子明"的父节点,选择索引为1的图像Set nodx = TreeView1.Nodes.Add("蒲子明", tvwChild, "child01", "收件箱", 3) '在"蒲子明"父节点下建立"收件箱"子节点,选择索引为3的图像Set nodx = TreeView1.Nodes.Add("蒲子明", tvwChild, "child02", "发件箱", 3) '在"蒲子明"父节点下建立"发件箱"子节点,选择索引为3的图像CunZai = FalseEnd SubPrivate Sub TreeView1_Expand(ByVal Node As MSComctlLib.Node) Node.ExpandedImage = 2 '节点被展开时,选择索引为2的图像End SubPrivate Sub TreeView1_NodeClick(ByVal Node As MSComctlLib.Node) If TreeView1.SelectedItem.Children = 0 Then '检查是否有子节点,0为无For I = 1 To TreeView1.Nodes.CountIf TreeView1.Nodes(I).Selected ThenMsgBox "您选择的是:“" & TreeView1.Nodes(I).FullPath & "”子节点!"'系统提示End IfNext IEnd If End Sub。
VFP6.0中ActiveX控件TreeView 使用实例ActiveX control TreeView using instances in VFP6.0ActiveX controls have long been used as an important tool for most program developers. Since it has nothing to do with the development language, you can use ActiveX controls on any software platform that supports ActiveX controls. Just as freely as using WINDOWS controls. However, many problems met ActiveX in specific to a certain development tools to use, this in a lot of publication of the article have often been discussed, but most are for Vc, Delphi, VB, PB and other development platform under the ActiveX control. In fact, the use of ActiveX controls in the above platform can basically help in its function, developers in accordance with their example, and ultimately can find the ActiveX control properties, methods, the use of events instructions. Even some development tools have made it convenient for developers to use some ActiveX controls as their common form controls.But in the VFP development platform, to use the ActiveX control as the development tool that lucky, because the VFP was not related to the grammatical descriptions and examples, the VFP developers feel embarrassed and confused. Because there are very few articles on this subject. Therefore, the author is in the development of "real estate sales software" as an example to introduce the specific use of TreeView controls in VFP, for the sake of the author of the same VFP colleagues reference.First, introduce the TreeView controlThe TreeView control displays a hierarchical list of Nodeobjects, each of which consists of a tag and an optional bitmap Node. TreeView is typically used to display document titles, index entries, files and directories on disk, or other kinds of information that can be effectively layered.The Node object is an item in the TreeView control that contains images and text. The Nodes collection contains one or more Node objects. Syntax: treeview.Nodes, treeview.Nodes.Item (index). You can use standard collection methods (such as Add and Remove methods) to operate Node objects. You can access each element in the collection by its index or the unique key stored in the Key property. To select the specified Node object, you must refer to it through its Index attribute or the value of the Key property.Add a Node object in the Nodes collection of the Treeview control: object.Add (relative, relationship, key, text, image, selectedimage). The Nodes collection is a collection based on 1. When a Node object is added, it is assigned an index number that is stored in the Index attribute of the Node object. The Index attribute value of this latest member is the value of the Count property of the Node collection. Because the Add method returns a reference to the newly created Node object, it is very convenient to use this reference to set the properties of the new Node. Here are a few properties of the node:Relative is optional. That represents the index number or key value of the existing Node object. The relationship between the new node and the existing node can be found in the next parameter, relationship.Relationship is optional. That represents the relative position of the specified Node object, as in the settings value. The setting value for relationship is:TvwFirst is a constant, and 0 is a value. It represents the node of the head. The Node and the nodes named in the relative are on the same floor and are located before all the same layer nodes.TvwLast is a constant, and 1 is a value. That represents the last node. The Node and the nodes named in the relative are on the same floor and are located behind all the same layer nodes. Any successive addition of nodes may be at the end of the last added nodeTvwNext is a constant, and 2 is the default. It represents the next node. The Node is located after the named node in relative.TvwPrevious is a constant, and 3 is a value. That represents the previous node. The Node is located before the named node in relative.TvwChild is a constant, and 4 is the default. It represents a child node. The Node becomes the child node of the node named in relative.Note that if the Node object is not named in the relative, the new node is placed at the last position of the top level of the node.Key is optional. It represents the only string in the node thatcan be used to retrieve Node using the Item method.Text is required. That represents the string that appears in Node, that is, the name of the node.Index is an integer or string that uniquely identifies a member of the Nodes collection. The integer is the value of the Index property, and the string is the value of the Key property.The FullPath property, which returns the full qualified path of the Node object referenced in the TreeView control. When given to the property as a string variable, the string is set to the FullPath node with the specified index.The Indentation property returns or sets the indent width of the object in the control.The LabelEdit property returns or sets a value that determines whether the label of the Node object in the TreeView control can be edited.Two, source code exampleIn this program, the TreeView control can implement the four layers of relations including the project, the building, the unit and the floor. Users simply click each layer of nodes "+" / "-", you can intuitively observe a project contains several buildings, a building contains several units, a unit and how many floors. By using the table GRID of each page in the page frame PAGEFRAME, you can add records in the corresponding tables and display the corresponding details in the GRID as longas you double-click each layer of nodes. It is worth noting that the program can realize the display of a number of projects, the project node and the project node is a parallel relationship between the same level, only second projects, the first node after the first row. The building node is the sub node of the project node, and the unit node is the sub node of the building node, and the floor node is the child node of the unit node.Source 1, TreeView control initialization work, that is, the form of the Olecontrol1.init event, fill in the source code 1, all the code.Source 2 implementation and page frame, show the corresponding details of the node, that is, the form of theOlecontrol1.NodeClick event, fill in the source code 2 all the code.Source code 1, as follows:LOCAL, M.L_XMCOUNT, I, J, K, L, M.L_NODES, M.L_LYCOUNT,M.L_DYCOUNT, M.L_LCCOUNTTHIS.NODES.CLEAR and remove all nodesBELEDIT=1 can edit node labelTHIS.Indentation=10 and indentation width of 10 pixelsSELECT SF_XMXXSet Dele onM.L_XMCOUNT=RECCOUNT ()FOR I=1 TO M.L_XMCOUNTSELECT SF_XMXXGO IIf! Delete ()(M.L_NODES=THIS.NODES.ADD,'XM'+XM_BH, and XM_MC) to join the first set of nodes and node KEY=XM, TEXT= project.M.L_NODES.EXPANDED=.T. and all the nodes can be foldedM.L_NODES.FORECOLOR=RGB (0,0255) and all nodes set the foreground colorM.P_XMBH=XM_BH=REQUERY ('VIEW_XMLY')M.L_LYCOUNT=RECCOUNT ('VIEW_XMLY')IF M.L_LYCOUNT>0FOR J=1 TO M.L_LYCOUNTSELECT VIEW_XMLYGO JIf! Delete ()And to the 'projects' parent node join node''KEY=LY TEXT= building, the actual number of buildingsTHIS.NODES.ADD ('XM'+SF_XMXX.XM_BH, 4,'LY'+VIEW_XMLY.LY_BH, VIEW_XMLY.LY_SJBH)M.P_LYBH=VIEW_XMLY.LY_BH=REQUERY ('VIEW_XMDY')M.L_DYCOUNT=RECCOUNT ('VIEW_XMDY')IF M.L_DYCOUNT>0FOR K=1 TO M.L_DYCOUNTSELECT VIEW_XMDYGO KIf! Delete ()To the 'building' parent node and child nodes' join unit'KEY=DY, TEXT= unit numberTHIS.NODES.ADD ('LY'+VIEW_XMLY.LY_BH, 4,'DY'+VIEW_XMDY.DY_BH, ALLTRIM (STR (VIEW_XMDY.DY_SJBH)) + 'unit')M.P_DYBH=VIEW_XMDY.DY_BH=REQUERY ('VIEW_XMLC')M.L_LCCOUNT=RECCOUNT ('VIEW_XMLC')IF M.L_LCCOUNT>0FOR L=1 TO M.L_LCCOUNTSELECT VIEW_XMLCGO LIf! Delete ()To the 'unit' parent node and child nodes join ''KEY=LC TEXT= floor, the actual floor numberTHIS.NODES.ADD ('DY'+VIEW_XMDY.DY_BH, 4,'LC'+VIEW_XMLC.LC_BH, ALLTRIM (STR (VIEW_XMLC.LC_SJCH)) + 'layer')EndifENDFORENDIFEndifENDFORENDIFEndifENDFORENDIFEndifENDFORSource code 2 is as follows:* * * ActiveX control event * * *LPARAMETERS node* * * ActiveX, Contro1l, Event * * *LOCAL, M.L_NODES, M.l_selected,l_indexm.l_selected = thisform.olecontrol1.selecteditem.index m.l_nodes =上。
treeview tooltiptext 用法案例在中,TreeView控件没有直接的TooltipText属性,但是您可以通过结合ToolTip 控件和TreeView控件的Tag属性来实现类似的效果。
下面是一个简单的例子:首先,在您的窗体上放置一个TreeView控件和一个ToolTip控件。
vbnet复制代码Dim treeView As New TreeView()Dim toolTip As New ToolTip()' 添加一些节点到TreeView中treeView.Nodes.Add("Node 1")treeView.Nodes(0).Nodes.Add("Child Node 1")treeView.Nodes(0).Nodes.Add("Child Node 2")treeView.Nodes.Add("Node 2")然后,您可以遍历TreeView的节点并为每个节点设置ToolTip文本。
这个文本将被显示当用户将鼠标悬停在节点上时。
vbnet复制代码For Each node As TreeNode In treeView.Nodes' 设置ToolTip文本toolTip.SetToolTip(node, "Tooltip text for " & node.Text)' 如果节点有子节点,递归设置子节点的ToolTip文本If node.Nodes.Count > 0ThenFor Each childNode As TreeNode In node.NodestoolTip.SetToolTip(childNode, "Tooltip text for " & childNode.Text)NextEnd IfNext现在,当您将鼠标悬停在TreeView的节点上时,应该能看到相应的ToolTip文本。
VB中TreeView的用法和几个实例VB中TreeView的用法和几个实例*****************************************1、为树状浏览器控件添加节点和子节点用ADD方法添加一个新节点到树状浏览器的NODES集合时,可以声明它是和已存在的节点所联系起来的。
通常使用ADD方法,其语法如下:Nodes.Add(relative,[relationship][,key][,text][,image][,selecte dimage])各个参数的意义如下:relationship 参数是通过关系节点参数与新节点连接的另一个节点;relationship 参数可能是以下情况:tvwlast--1;该节点置于所有其他的在relative中被命名的同一级别的节点的后面tvwNext--2;该节点置于在relative中被命名节点的后面tvwPrevius--3;该节点置于在relative中被命名的节点的前面tvwChild--4;该节点成为在relative中被命名的节点的的子节点下面是一个例子:Dim node1,node2,node3,node4 as Nodeset Node1=TreeView1.Nodes.AddTreeView1.Nodes(1).text="node1"TreeView1.Nodes(1).key="node1"Set node2=treeview.nodes.add("node1",tvwChild,"node2") TreeView1.Nodes(2).text="node2"TreeView1.Nodes(2).key="node2"依次插入节点即可。
2、为节点插入图象treeview1.node(3).image="leaf"注意我们一般从imagelist中指定图象3、处理节点的点击,怎样才能知道树状浏览器的哪一个节点被点击了呢?可以用NodeClick 事件:public sub treeview1_nodeclick(byval node as comctllib.node) text1.text="you click"&node.textend sub*********************************************************2、TreeView的使用,及选中其中指定的节点’=============Private Sub Command1_Click()Dim nodeY As NodeFor Each nodeY In TreeView1.NodesIf CStr(Trim(nodeY.Text)) = "ff" ThennodeY.Selected = TrueTreeView1.SetFocusExit ForEnd IfNextPrivate Sub Form_Load()/doc/95892732.html,mandType = adCmdTextRs1.RecordSource = "select distinct biao,zu from test order by zu"Rs1.RefreshDim Rs As ADODB.RecordsetSet Rs = Rs1.RecordsetSet nodX = TreeView1.Nodes.Add(, , "r", "报表组 ")i = 0Dim TempString As StringDim TempKey As LongDo Until Rs.EOF Or Rs.BOFIf TempString = Rs!zu ThenSet nodeX = TreeView1.Nodes.Add("Z" & TempKey, tvwChild, "B" & i, Rs!biao)ElseSet nodX = TreeView1.Nodes.Add("r", tvwChild, "Z" & i, Rs!zu) Set nodeX = TreeView1.Nodes.Add("Z" & i, tvwChild, "B" & i, Rs!biao)TempString = Rs!zuTempKey = iEnd IfRs.MoveNexti = i + 1Loop**********************************************************3'功能:选择Treeview节点下所有节点'----------------------------------------------------------------------------Private Sub Form_Load()TreeView1.Checkboxes = TrueTreeView1.Nodes.Add , "R", "root", "root"TreeView1.Nodes.Add "root", tvwChild, "key1", "aa"TreeView1.Nodes.Add "key1", tvwChild, "key11", "ccc"TreeView1.Nodes.Add "root", tvwChild, "key2", "bb"TreeView1.Nodes.Add "key2", tvwChild, "key21", "ddd"TreeView1.Nodes.Add "key2", tvwChild, "key211", "eee"For I = 1 To TreeView1.Nodes.CountTreeView1.Nodes(I).Expanded = TrueNextEnd SubPrivate Sub CheckChild(ByVal Node As MSComctlLib.Node, ByVal bCheck As Boolean, Optional ByVal bNext As Boolean = True, Optional ByVal bChild As Boolean = True)If Not Node Is Nothing ThenNode.Checked = bCheckIf Node.Children And bChild ThenCall CheckChild(Node.Child, bCheck, True, True) '对子节点End IfIf bNext ThenCall CheckChild(Node.Next, bCheck, True, bChild) '对同一层节点End IfEnd IfEnd SubPrivate Sub TreeView1_NodeCheck(ByVal Node As MSComctlLib.Node)Call CheckChild(Node, Node.Checked, False, True) '处理子节点End Sub。
中TreeView控件的使用在中TreeView(树型结构)控件是显示节点(Node)对象的级层结构它通常用于显示一些有等级结构的信息我们最为熟悉的就是Windows资源管理器左边显示文件和文件夹的窗口在工具箱中TreeView 控件的图标如下图一所示TreeView控件的每个节点(Node对象)包含了一个标签和可选的点位图每个节点又可能包含有若干个的子节点可以通过控制某个节点来展开显示或者折叠隐藏它所包含的子节点一 TreeView 控件的一些常用属性CheckBoxes 属性指示是否在树视图控件中的树节点旁显示复选框FullRowSelect 属性当 FullRowSelect 为 true 时选择突出显示将跨越树视图的整个宽度即整个显示区域的宽度而不仅仅是树节点标签的宽度如果 ShowLines 设置为 true 则将忽略 FullRowSelect 属性HideSelection 属性指示选定的树节点是否即使在树视图已失去焦点时仍会保持突出显示HotTracking 属性如果 HotTracking 属性设置为 true 那么当鼠标指针移过每个树节点标签时树节点标签都将具有超级链接的外观Underline 字体样式将应用于 Font 而 ForeColor 将设置为蓝色从而使标签显示为链接注意如果CheckBoxes 属性设置为true HotTracking 属性将失效Indent 属性设置每个子树节点级别的缩进距离(以像素为单位) ItemHeight 属性设置树视图控件中每个树节点的高度Nodes 属性获取分配给树视图控件的树节点集合这个属性是TreeView 控件最重要的属性之一我们下文将会对它进行更加的详细的说明PathSeparator 属性树节点路径(TreeNode FullPath 属性)所使用的分隔符串默认为反斜杠字符(\) 树节点路径包括一组由PathSeparator 分隔符串分隔的树节点标签标签的范围为根树节点到所需的树节点如下代码我们可以获得当前选中的节点的路径MessageBox Show(TreeView SelectedNode FullPath)SelectedNode 属性获取或设置当前在树视图控件中选定的树节点如果没有选定任何节点则 SelectedNode 属性则为Nothing ShowLines 属性指示是否在树视图控件中的树节点之间绘制连线ShowPlusMinus 属性指示是否在包含子树节点的树节点旁显示加号 (+) 和减号 ( ) 按钮ShowRootLines 属性指示是否在树视图根处的树节点之间绘制连线如下图二所示为ShowLines 属性ShowPlusMinus 属性ShowRootLines 属性都设置为True的情形二为TreeView 控件添加节点TreeView 控件的 Nodes 属性包含了它所有的节点下面我们就来了解如何为树状控件添加节点通过树节点编辑器添加选中TreeView 控件在它的属性对话框中找到Nodes 属性然后单击它后面的省略号弹出树节点编辑器如下图三所示然后通过编辑器上的添加根来添加根节点通过添加子级来为选中的节点添加子节点通过删除来删除选定的节点标签输入框确定节点的名称注意只有设置了TreeView 控件的ImageList 属性才能选择设置节点的图像通过编程方式添加节点给TreeView添加结点用到的是Nodes Add 方法首先选定要添加子结点的结点才能应用这个方法TreeView中的结点的组织关系是父结点管理子结点的关系也就是说子结点组成的集合就是父结点的 Nodes 属性子结点的 Index 属性是根据其在子结点集合中的位置而决定的而不是整棵树中结点的位置根据这个特点若想找到指定结点须按以下的语法TreeViewName Nodes Item(Index ) Nodes而添加结点的方法为TreeViewName Nodes Item(Index ) Nodes Add( NodeText )或TreeViewName Nodes Item(Index ) Nodes Add( objNode ) 如下代码所示为选中的节点添加一个子节点TreeView SelectedNode Nodes Add( )编程删除节点使用Nodes属性的Remove 方法删除单个节点也可以使用Clear 方法清除所有的节点如下代码所示删除选定的节点TreeView Nodes Remove(TreeView SelectedNode)清除TreeView 控件的所有节点TreeView Nodes Clear()示例演示我们现在用一个实例来看如何使用Nodes属性来实现代码编程添加删除树形控件的节点首先为设计如下图四所示的程序界面其中有四个Button 控件一个TreeView 控件为添加根节点按钮添加如下代码TreeView Nodes Add( 根节点& (TreeView GetNodeCount(False) + ))注意GetNodeCount方法为获得本级别的节点数可以通过参数False来指定不包括它的子节点为添加子节点按钮添加如下代码Dim node As TreeNode = TreeView SelectedNodeIf Not node Is Nothing Thennode Nodes Add( 子节点 & (node GetNodeCount(False) + ))ElseMessageBox Show( 没有选中任何节点 )End If注意 TreeNode GetNodeCount 方法返回的是分配给 Nodes 集合的子树节点的数目为删除单个节点按钮添加代码Dim node As TreeNode = TreeView SelectedNodeIf node Is Nothing ThenMessageBox Show( 没有选中任何节点 )ElseTreeView Nodes Remove(node)End If为删除所有节点按钮添加代码TreeView Nodes Clear()代码添加完毕后运行程序分别使用添加根节点添加子节点为控件添加节点如下图五所示然后再试验删除节点的效果三访问控件的所有节点因为Nodes集合中所包含的只是本级节点的集合如果某个Node 包含有子节点并不会从当前的Nodes体现出来如下代码所示我们只能访问到所有的根节点而不是所有的节点假定我们是在前面示例的基础上添加一个名为遍历节点的按钮然后在该按钮的Click事件中添加如下代码Dim node As TreeNodeDim str As String =For Each node In TreeView Nodesstr = str & node Text & vbCrNextMessageBox Show(str)node = Nothing运行后先分别为控件添加若干个根节点与子节点然后单击遍历节点按钮效果如下图六所示很明显我们遍历了Nodes集合但是并没有如期访问到子节点怎么解决这个问题呢?请看下一页如上页的问题我们假设一个根节点的Nodes集合为Nodes 该集合中的一个Node节点为Node Node 下有若干个子节点我们把它的子节点的集合称为Nodes 我们用For Each 遍历Nodes 时它访问到Node 但不会访问Nodes 集合如果我们要访问Nodes 就需要像遍历Nodes 一样遍历Nodes 解决办法如下首先建立一个过程用于遍历一个Node节点下的子节点Private Sub PrintNode(ByVal N As TreeNode)Debug WriteLine(N Text)Dim node As TreeNodeFor Each node In N NodesPrintNode(node)NextEnd Sub然后把遍历节点的Click事件中修改为如下代码Dim node As TreeNodeFor Each node In TreeView NodesPrintNode(node)Nextnode = Nothing运行后先分别为控件添加若干个根节点与子节点然后单击遍历节点按钮然后查看输出窗口效果如下图七所示可以发现已经能真正地遍历了所有节点lishixinzhi/Article/program/net/201311/11617。
vb TreeView 控件应用实例2009-11-14 20:52TreeView 控件应用实例:将 TreeView 绑定到 Biblio.mdb 数据库应用示例:DataTree.vbp本章的代码示例是从应用示例 DataTree.vbp which is listed in the Samples directory 中得到的。
可将数据库中的数据绑定到 TreeView 控件。
下面的示例将 TreeView 控件绑定到 Biblio 数据库,该数据库可以在 Visual Basic CD 中找到。
该应用实例将 Publishers 表作为树节点的第一层。
如果一个出版商对应于一个或多个书名,则这些书名将作为该出版商的子节点加入树中。
图 2.42 与数据绑定的 TreeVew 控件下面的代码用到了如下对象:Data Access Object Library(3.5)名为“frmDataTree”的 Form 对象名为“tvwDB”的 TreeView 控件名为“cmdLoad”的 CommandButton 控件将 Biblio.mdb 数据库绑定到 TreeView 控件在工程中添加对数据访问对象(DAO 3.0)的引用。
为 Database 和 Node 对象创建模块级的变量。
在 Form Load 事件中,用 OpenDatabase 语句将 Database 对象变量设置为 Biblio 数据库。
用 Nodes 集合的 Add 方法创建顶层的节点对象。
在 CommandButton 的 Click 事件中,创建两个 Recordset 变量,并将它们设置为Publishers 和 Titles 表。
用“Do Until”语句为表中的每个出版商创建一个 Node 对象。
对每个出版商,在 Titles 记录集中检查匹配的 PubID 字段;为每个匹配项添加一个子节点。
在工程中添加对数据访问对象(DAO 3.5)的引用要将数据库绑定到 TreeView 控件,必须先添加对当前版本的数据访问对象(DAO)的引用。
为 Database 对象和 Node 对象创建模块级的变量由于需要在一个会话中多次访问 Biblio.mdb 数据库,如果创建一个模块级的 Database 对象,保持一个打开数据库,将有助于提高效率。
此后,不需要打开数据库即可访问它。
在窗体的声明部分,键入如下内容:Private mDbBiblio As Database如果希望该数据库还可被其它模块使用,可以用 Public 语句,并重命名该变量,以表明它是全局的,例如 gDbBiblio。
在创建 Node 对象时,在 Set 语句中(如下所示)使用 Node 类型的变量。
Dim TempNode As NodeSet TempNode = tvwDB.Nodes.Add()虽然可以在添加 Node 对象时创建变量,更有效的方式是声明一个模块级的 Node 对象变量,并用它创建所有的 Node 对象。
在上述声明部分再键入:Private mNode As Node用 OpenDatabase 语句将 Database 对象变量设置为 Biblio 数据库Form 对象的 Load 事件中可以初始化 Database 变量。
代码如下:Set mDbBiblio = DBEngine.OpenDatabase("BIBLIO.MDB")在成功地初始化 Database 对象变量后,就可以在该模块的代码中的任何位置自由地访问它了。
Form Load 事件:用 Nodes 集合的 Add 方法创建顶层的 Node 对象至此,Database 对象变量已经被初始化为 Biblio 数据库,现在可以创建树中的第一个节点,并将打开的数据库的名称赋予它。
首先必须用 Node 集合的 Add 方法创建第一个 Node 对象。
还要使用 Set 语句将其赋给 mNode 对象变量,如下所示:Set mNode = tvwDB.Nodes.Add() ' 创建第一个节点。
mNode.Text = 注意,在上面的代码中,在创建 Node 的同时用 Set 语句将其赋给了 mNode 对象变量。
由于 mNode 变量现在包含了新创建的 Node 对象,可以对该 Node 对象的属性进行赋值。
在上述情况下,Database 的名称(即 Database 对象的 Name 属性)已经被赋给了新节点的Text 属性。
CommandButton Click 事件:创建两个 Recordset 变量,并将它们分别设置为 Publishers 和 Titles 表本应用实例假定存在名为“cmdLoad”的按钮,并且当用户单击它时,置入 Biblio 数据库中的两个表到 TreeView 控件中。
为此,必须首先在该按钮的 Click 事件中声明两个 DAO 对象变量。
第一个变量 rsPublishers 用来包含 Publishers 表。
第二个变量 rsTitles 用来包含 Titles 表。
下面的代码声明了这两个变量,并用 OpenRecordSet 方法将表赋给变量:Dim rsPublishers As RecordsetDim rsTitles As RecordsetSet rsPublishers = mDbBiblio. _OpenRecordset("Publishers", dbOpenDynaset)Set rsTitles = mDbBiblio. _OpenRecordset("titles", dbOpenDynaset)用 Do Until 语句为表中的每个出版商创建一个 Node 对象现在有两个打开的记录集,可以遍历每个记录集,创建 Node 对象,并为该对象的 Text 属性赋予合适的值。
首先,必须遍历 Publishers 表,并为该表中的每个出版商创建一个 Node 对象。
下列简化了的代码可以用一句话概括为,“逐个处理每个记录,直到记录集的末尾:创建Node 变量,并将 Title 字段的值赋给其 Text 属性,移到下一记录并重复”:Do Until rsPublishers.EOFSet mNode = tvwDB.Nodes.Add(1, tvwChild)mNode.Text = rsPublishers!NamersPublishers.MoveNextLoop注意,在上面的 Add 方法中用了两个参数。
第一个参数(1)是我们希望添加入节点的 Node 的 Index 属性。
也就是说,希望所有的出版商节点成为第一个(根)节点(在 Form 的 Load 事件中创建的)的子节点。
第二个参数使用了常数 (tvwChild),该常数指定新的 Node 将成为编号为“1”的 Node 的子节点。
对每个出版商,在 Titles 记录集中检查匹配的 PubID 字段;为每个匹配项添加一个子节点上面的代码将 Publishers 表的内容作为第一层填入 TreeView 中。
然而,我们还希望能够进入更深一层,为每个出版商节点增加子节点。
每个子节点代表该出版商印刷的一本书。
为了做到这一点,如果有了对新创建的出版商节点 (mNode) 的引用,只要遍历 Titles 记录集,并检查每条记录的 PubID 字段即可。
如果该字段与 Publishers 记录集中的 PubID 字段相匹配,则该书是由当前的出版商出版的。
但是,在能够为 mNode 添加节点之前,还必须先将 mNode 的 Index 属性赋给一个变量 (intIndex),如下所示:intIndex = mNode.Index然后就可以在 Add 方法中使用该变量了,Add 方法需要用来加入子节点的 Node 对象的Index 属性:Set mNode = tvwDB.Nodes.Add(intIndex, tvwChild)如下简化的代码可被表述为“直到 Recordset 的结尾:创建子 Node 对象,并将 Title 字段的值赋给它的 Text 属性;移动到下一记录并重复上述操作”:Do Until rsTitles.EOFIf rsPublishers!PubID = rsTitles!PubID ThenSet mNode = tvwDB.Nodes.Add(intIndex, tvwChild)mNode.Text = rsTitles!Title 'Text 属性。
End IfLoop完成代码上面的代码显示了用两个相关的表填成一个表的基本策略。
全部代码如下:'必须设置对 DAO 3.5 的引用。
'在声明部分,声明模块级的对象变量:Private mDbBiblio As DatabasePrivate mNode As NodePrivate Sub Form_Load()'在 Form_Load 事件中,设置对象变量,'并创建 TreeView 控件的第一个 Node 对象。
Set mDbBiblio = DBEngine.Workspaces(0). _OpenDatabase("BIBLIO.MDB")tvwDB.Sorted = TrueSet mNode = tvwDB.Nodes.Add()mNode.Text = "Publishers"mNode.Tag = '设置 Tag 属性。
mNode.Image = "closed" '设置 Image'属性End SubPrivate Sub cmdLoad_Click()'声明 DAO 对象变量,'并将记录集赋予它们。
Dim rsPublishers As RecordsetDim rsTitles As RecordsetSet rsPublishers = mDbBiblio. _OpenRecordset("Publishers", dbOpenDynaset)Set rsTitles = mDbBiblio. _OpenRecordset("titles", dbOpenDynaset)'移到第一条记录。
rsPublishers.MoveFirstDim intIndex As Integer '用于索引的变量。
'直到最后一条记录 (EOF):添加一个 Node 对象,'并用 Name 字段作为新'Node 对象的文本。