使用treeView控件展示目录树列表,并进行一系列的操作。
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TreeViewTest
{
public partial class frmTreeView : Form
{
private bool isfirst = true;//默认选择某个节点标志
public frmTreeView()
{
InitializeComponent();
}
private void btnOpdir_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();//选择目录
if (dlg.ShowDialog()==DialogResult.OK)
{
ShowTreeView(treeView1,dlg.SelectedPath);
}
}
//treeView1事件---取消默认选择某一节点
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (isfirst)
{
e.Cancel = true;
isfirst = false;
}
}
//treeView1事件---选中或取消选中树节点上的复选框
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)//通过鼠标操作
{
if (e.Node.Checked == true)
{
AllNodesChecked(e.Node, true);//选中节点,其子节点也选中
}
else if (e.Node.Checked == false)
{
AllNodesChecked(e.Node, false);//取消节点选中,其子节点也取消选择
if (e.Node.Parent != null) //如果节点存在父节点,取消父节点的选择
{
FuNodeNoChecked(e.Node, false);//取消子节点选中,其父节点也取消选择
}
}
}
}
//展示目录树结构
private void ShowTreeView(TreeView treeview, string path)
{
try
{
treeview.Nodes.Clear();//清空所有
TreeNode rootNode = new TreeNode(path);//载入显示
rootNode.Tag = path;//树节点数据
rootNode.Text = path;//节点标签显示内容
treeview.Nodes.Add(rootNode);//添加根目录
DirectoryInfo dirs = new DirectoryInfo(path);//创建目录对象
DirectoryInfo[] dir = dirs.GetDirectories();//目录下的所有子目录
int dirCount = dir.Count();//子目录个数
for (int i = 0; i < dirCount; i++)
{
rootNode.Nodes.Add(dir[i].Name);//在根节点下添加子节点(dir[i].Name目录名称)
string pathNode = path + "\\" + dir[i].Name;//子节点的全路径
GetNode(rootNode.Nodes[i], pathNode);//遍历目录下的子目录
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n出错位置");
}
}
//递归遍历子目录
private bool GetNode(TreeNode treeNode, string path)
{
if (Directory.Exists(path) == false)
{
return false;
}
DirectoryInfo dirs = new DirectoryInfo(path);
DirectoryInfo[] dir = dirs.GetDirectories();
int dirCount = dir.Count();
if (dirCount == 0)
{
return false;
}
for (int i = 0; i < dirCount; i++)
{
treeNode.Nodes.Add(dir[i].Name);
string pathNode = path + "\\" + dir[i].Name;
GetNode(treeNode.Nodes[i], pathNode);//递归遍历目录下的子目录
}
return true;
}
/// <summary>
///选中节点,其子节点也选中
/// </summary>
/// <param name="currNode">当前选择的节点</param>
/// <param name="state">选择状态</param>
private void AllNodesChecked(TreeNode currNode, bool state)
{
TreeNodeCollection nodes = currNode.Nodes;
if (nodes.Count > 0)
{
foreach (TreeNode tn in nodes)
{
tn.Checked = state;
AllNodesChecked(tn, state);
}
}
}
/// <summary>
/// 取消节点选中,其父节点也取消选择
/// </summary>
/// <param name="treeNode">当前节点</param>
/// <param name="state">选择状态</param>
private void FuNodeNoChecked(TreeNode currNode, bool state)
{
TreeNode fuNode = currNode.Parent;
fuNode.Checked = state;
if (currNode.Parent.Parent != null)
{
FuNodeNoChecked(currNode.Parent, state);
}
}
}
}