日期:2014-05-17 浏览次数:21143 次
可以看到,项的前面都显示了加号(+),而且读取了磁盘的文件。代码如下
主程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileManager
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
/// <summary>
/// 加载逻辑磁盘文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Main_Load(object sender, EventArgs e)
{
DriveInfo[] myDrivers = DriveInfo.GetDrives();
foreach (DriveInfo di in myDrivers)
{
if (di.IsReady)
{
TreeNode tNode = new TreeNode(di.Name.Split(':')[0]);
tNode.Name = di.Name;
tNode.Tag = tNode.Name;
tNode.Nodes.Add("DUMMY");
tvRoot.Nodes.Add(tNode);
}
}
//添加鼠标右键的事件
this.tvRoot.ContextMenuStrip = new TreeViewContextMenu().Load();
}
/// <summary>
/// TreeView必须处理的两个事件之一
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvRoot_AfterSelect(object sender, TreeViewEventArgs e)
{
e.Node.Expand();
}
/// <summary>
/// TreeView必须处理的两个事件之一
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvRoot_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
TreeViewItems.Add(sender, e);
}
}
}
为TreeView添加TreeNode的代码:
public static class TreeViewItems
{
public static void Add(object sender, TreeViewCancelEventArgs e)
{
e.Node.Nodes.Clear();
TreeNode tNode = e.Node;
//MessageBox.Show(tNode.Name);
string path = tNode.Name;
string[] dics = Directory.GetDirectories(path);
foreach (string dic in dics)
{
TreeNode subNode = new TreeNode(new DirectoryInfo(dic).Name);
subNode.Name = new DirectoryInfo(dic).FullName;
subNode.Tag = subNode.Name;
subNode.Nodes.Add("");
tNode.Nodes.Add(subNode);
}
string[] files = Directory.GetFiles(path);
foreach (string aFile in files)
{
TreeNode subNode = new TreeNode(new FileInfo(aFile).Name);
subNode.Tag = aFile;
subNode.Name = subNode.Text;
tNode.Nodes.Add(subNode);
}
}
}
这里注意e.Node.Nodes.Clear();还有给节点的下面添加一个空的节点:如
tNode.Nodes.Add