Treeview 控件:名称 Treeview1;
Imagelist 控件:名称 Imagelist1,并在该控件中放置三张个性图片(32×32),建立索引1、2、3;(方法:在Imagelist 控件上单击鼠标右键选择属性)
Label 控件:名称分别为Lab(0)、Lab(1),Caption分别为“父节点:”、“子节点:”;
Textbox 控件:名称分别为Txt(0)、Txt(1),text都为“”;
commandbutton 控件:名称为系统默认,Caption分别为“添加”、“展开”、“收起”、“排序”、“删除”、“退出”;
将下列代码加入到代码框:
Option Explicit
Dim I As Integer
Dim J As Integer
Dim nodx As Node
Dim CunZai As Boolean 定义变量
Private Sub Command1_Click()
If Txt(0).Text <> "" And Txt(1).Text <> "" Then 不允许建立零字节的父节点和子节点
CunZai = False
J = TreeView1.Nodes.Count
For I = 1 To TreeView1.Nodes.Count 检查新输入的父节点名称是否存在
If TreeView1.SelectedItem.Children > 0 Then
If Txt(0).Text = TreeView1.Nodes(I).Text Then CunZai = True
End If
Next I
If 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 If
TreeView1.Refresh
ElseIf Txt(0).Text = "" Then MsgBox "请输入父节点名称!", vbInformation, "警告!"
系统提示
ElseIf Txt(1).Text = "" Then MsgBox "请输入子节点名称!", vbInformation, "警告!"
End If
End Sub
Private Sub Command2_Click()
For I = 1 To TreeView1.Nodes.Count
TreeView1.Nodes(I).Expanded = True 展开所有节点
Next I
End Sub
Private Sub Command3_Click()
For I = 1 To TreeView1.Nodes.Count
TreeView1.Nodes(I).Expanded = False 收起所有节点
Next I
End Sub
Private Sub Command4_Click()
TreeView1.Sorted = True 排列顺序
End Sub
Private Sub Command5_Click()
If TreeView1.SelectedItem.Index <> 1 Then
TreeView1.Nodes.Remove TreeView1.SelectedItem.Index 删除选定的节点
End If
End Sub
Private Sub Command6_Click()
End 退出程序
End Sub
Private 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 = False
End Sub
Private Sub TreeView1_Expand(ByVal Node As MSComctlLib.Node)
Node.ExpandedImage = 2 节点被展开时,选择索引为2的图像
End Sub
Private Sub TreeView1_NodeClick(ByVal Node As MSComctlLib.Node)
If TreeView1.SelectedItem.Children = 0 Then 检查是否有子节点,0为无
For I = 1 To TreeView1.Nodes.Count
If TreeView1.Nodes(I).Selected Then
MsgBox "您选择的是:“" & TreeView1.Nodes(I).FullPath & "”子节点!"
系统提示
End If
Next I
End If
End Sub