可以看到,項的前面都顯示了加號(+),而且讀取了磁盤的文件。代碼如下
主程序代碼:
[csharp]
<span style="font-size:14px;">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;
<span style="color:#ff0000;">tNode</span>.<span style="color:#ff0000;">Nodes</span>.<span style="color:#ff0000;">Add</span><span style="color:#ff0000;">("</span><span style="color:#ff0000;">DUMMY</span><span style="color:#ff0000;">");</span>
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);
}
}
}</span>
為TreeView添加TreeNode的代碼:
[csharp]
<span style="font-size:14px;">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;
<span style="color:#ff0000;">subNode</span>.<span style="color:#ff0000;">Nodes</span>.<span style="color:#ff6666;">Add</span><span style="color:#ff0000;">("");</span>
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);
}
}
}</span>
這裡注意e.Node.Nodes.Clear();還有給節點的下面添加一個空的節點:如
tNode.Nodes.Add("DUMMY");
和
subNode.Nodes.Add("");
這些都是添加空節點的方式來顯示 “加號”。。。然後正式加載的時候刪掉