我需要有关如何将驱动器映射到树视图的帮助。我可以让我的驱动器显示,但我无法获得所有的子目录。我想把我的整个驱动器映射到树视图中。任何帮助,将不胜感激。这是我到目前为止所得到的。
string[] drives = Environment.GetLogicalDrives();
foreach (string dr in drives)
{
TreeNode node = new TreeNode(dr);
node.Tag = dr;
treeView1.Nodes.Add(node);
}
treeView1.CollapseAll();
答案 0 :(得分:2)
递归地执行:
private void fillTree() { // you allready had most of this
string[] drives = Environment.GetLogicalDrives();
foreach(string dr in drives) {
TreeNode node = RecursiveDirWalk(dr);
node.ImageIndex = 0; // drive icon
node.Tag = dr;
treeView1.Nodes.Add(node);
}
}
// now add this
private TreeNode RecursiveDirWalk(string path) {
TreeNode node = new TreeNode(path.Substring(path.LastIndexOf('\\')));
node.ImageIndex = 1; // dir icon
node.Tag = path;
string[] dirs = System.IO.Directory.GetDirectories(path);
for(int t = 0; t < dirs.Length; t++) {
node.Nodes.Add(RecursiveDirWalk(dirs[t]));
}
// Optional if you want files as well:
string[] files = System.IO.Directory.GetFiles(path);
for(int t = 0; t < files.Length; t++) {
TreeNode tn = new TreeNode(System.IO.Path.GetFileName(files[t]));
tn.Tag = files[t];
tn.ImageIndex = 2; // file icon
node.Nodes.Add(tn);
} // end of optional file part
return node;
}
答案 1 :(得分:0)
这是一个延迟加载版本:
private void fillTree() {
string[] drives = Environment.GetLogicalDrives();
foreach(string dr in drives) {
TreeNode node = new TreeNode(dr);
node.Tag = dr;
node.ImageIndex = 0; // drive icon
node.Tag = dr;
treeView1.Nodes.Add(node);
node.Nodes.Add(new TreeNode("?"));
}
treeView1.BeforeExpand += new TreeViewCancelEventHandler(treeView1_BeforeExpand);
}
void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
if((e.Node.Nodes.Count == 1) && (e.Node.Nodes[0].Text=="?")) {
RecursiveDirWalk(e.Node);
}
}
private TreeNode RecursiveDirWalk(TreeNode node) {
string path = (string)node.Tag;
node.Nodes.Clear();
string[] dirs = System.IO.Directory.GetDirectories(path);
for(int t = 0; t < dirs.Length; t++) {
TreeNode n = new TreeNode(dirs[t].Substring(dirs[t].LastIndexOf('\\')+1));
n.ImageIndex = 1; // dir icon
n.Tag = dirs[t];
node.Nodes.Add(n);
n.Nodes.Add(new TreeNode("?"));
}
// Optional if you want files as well:
string[] files = System.IO.Directory.GetFiles(path);
for(int t = 0; t < files.Length; t++) {
TreeNode tn = new TreeNode(System.IO.Path.GetFileName(files[t]));
tn.Tag = files[t];
tn.ImageIndex = 2; // file icon
node.Nodes.Add(tn);
} // end of optional file part
return node;
}
答案 2 :(得分:0)
以下是用于显示树的代码,该树仅包含首先显示的驱动器,当用户单击节点时添加到树中。此代码不会显示空驱动器。向每个节点添加图标留给学生练习:
select Month, Item,
(events + party + spirit + faith) as counts
from t;