继续上一节对目录的操作。本节主要建立了一个类似资源管理器的简单程序,当然仅仅是列出目录和文件,其他操作没有加上。
窗体设计界面如下:
设置了TreeView的根节点的Text和Tag属性为 我的电脑
当窗体载入时候,添加所有的磁盘分区到 我的电脑 下面:
Private Sub Form6_Load(sender As Object,e As EventArgs) Handles MyBase.Load Dim driveNode As TreeNode Dim drivers() As DriveInfo = DriveInfo.GetDrives For Each singleDrive In drivers driveNode = New TreeNode(singleDrive.Name) driveNode.Tag = singleDrive.Name tvPath.Nodes("root0").Nodes.Add(driveNode) Next End Sub
当点击了除根节点外的节点的时候:
Private Sub tvPath_AfterSelect(sender As Object,e As TreeViewEventArgs) Handles tvPath.AfterSelect Call showDirAndFiles(e.Node) End Sub ''' <summary> ''' 根据选择的TreeNode在lvPath中显示相应的文件夹或文件 ''' </summary> ''' <param name="selectedNode">点击的TreeNode</param> Private Sub showDirAndFiles(ByVal selectedNode As TreeNode) lvPath.Items.Clear() '选择的是根节点,则不处理 If selectedNode.Tag = "我的电脑" Then Exit Sub '清除该TreeNode下的子节点 selectedNode.Nodes.Clear() Dim nowpath As String = selectedNode.Tag Dim dir As New DirectoryInfo(nowpath) Dim nodeChild As TreeNode Dim lvChild As ListViewItem Try If dir.Exists Then '获得选定目录下的子目录 For Each dir_single As DirectoryInfo In dir.GetDirectories() '文件夹加入该TreeNode下 nodeChild = New TreeNode(dir_single.Name) nodeChild.Tag = dir_single.FullName selectedNode.Nodes.Add(nodeChild) 'lv中加入该文件夹 lvChild = New ListViewItem(dir_single.Name) lvChild.SubItems.Add("文件夹") lvPath.Items.Add(lvChild) Next '获得选定目录下的文件 For Each file_single As FileInfo In dir.GetFiles() 'lv中加入该文件 lvChild = New ListViewItem(file_single.Name) lvChild.SubItems.Add("文件") lvPath.Items.Add(lvChild) Next End If Catch ex As Exception MessageBox.Show("发生错误:" & ex.Message) End Try End Sub
运行效果如下:
TreeView的操作请参看《vb.net 教程 3-4 窗体编程 公共控件10 TreeView 1》
ListView的操作请参看《vb.net 教程 3-4 窗体编程 公共控件9 ListView 1》
学习更多vb.net知识,请参看 vb.net 教程 目录