treeview目录树问题
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] drivers = DriveInfo.GetDrives();//获取计算机上的所有逻辑驱动器名称
foreach (var item in drivers)
{
treeView1.Nodes.Add(item.ToString());
}
这里获得了盘符,也加载了,但是下面的代码怎么修改才能展开对应的子目录,谢谢
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
e.Node.Nodes.Cast<TreeNode>().ToList().ForEach(x =>
{
try
{
if (x.Nodes.Count == 0)
{
TreeNode[] nodes = new TreeNode[] { };
if (x.Tag.GetType() == typeof(DriveInfo))
{
var item = x.Tag as DriveInfo;
nodes = Directory.GetDirectories(item.Name)
.Select(y => new DirectoryInfo(y))
.Select(y => new TreeNode(y.Name) { Tag = y })
.ToArray();
}
if (x.Tag.GetType() == typeof(DirectoryInfo))
{
var item = x.Tag as DirectoryInfo;
nodes = Directory.GetDirectories(item.FullName)
.Select(y => new DirectoryInfo(y))
.Select(y => new TreeNode(y.Name) { Tag = y })
.ToArray();
}
x.Nodes.AddRange(nodes);
}
}
catch { }
});
}
------解决方案--------------------
http://www.cnblogs.com/sndnnlfhvk/archive/2011/03/31/2001065.html之前找资料的
------解决方案--------------------
如下修改即可
C# code
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] drivers = DriveInfo.GetDrives();//获取计算机上的所有逻辑驱动器名称
foreach (var item in drivers)
{
TreeNode tn = new TreeNode();
tn.Tag = item;
tn.Text = item.ToString();
treeView1.Nodes.Add(tn);
}
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode tn = e.Node;
try
{
if (tn.Nodes.Count == 0)
{
TreeNode[] nodes = new TreeNode[] { };
if (tn.Tag.GetType() == typeof(DriveInfo))
{
var item = tn.Tag as DriveInfo;
nodes = Directory.GetDirectories(item.Name)
.Select(y => new DirectoryInfo(y))
.Select(y => new TreeNode(y.Name) { Tag = y })
.ToArray();
}
if (tn.Tag.GetType() == typeof(DirectoryInfo))
{
var item = tn.Tag as DirectoryInfo;
nodes = Directory.GetDirectories(item.FullName)
.Select(y => new DirectoryInfo(y))
.Select(y => new TreeNode(y.Name) { T