在treeview asp.net中隐藏rootnode

时间:2013-08-22 14:31:44

标签: c# asp.net treeview nodes

如何在这种情况下隐藏rootnode“temp”文件夹? 我想在rootnode上设置一个CssClass。

TreeView TreeView1 = new TreeView();
    protected void Page_Load(object sender, EventArgs e)
    {
        BuildTree(@"C:\temp");
        form1.Controls.Add(TreeView1);
    }
    private void BuildTree(string root)
    {
        DirectoryInfo rootDir = new DirectoryInfo(root);
        TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
        TreeView1.Nodes.Add(rootNode);
        TraverseTree(rootDir, rootNode);
    }
    private void TraverseTree(DirectoryInfo currentDir, TreeNode currentNode)
    {
        foreach (DirectoryInfo dir in currentDir.GetDirectories())
        {
            TreeNode node = new TreeNode(dir.Name, dir.FullName);
            currentNode.ChildNodes.Add(node);
            TraverseTree(dir, node);
        }
        foreach (FileInfo file in currentDir.GetFiles())
        {
            TreeNode nodeFile = new TreeNode(file.Name, file.FullName);
            currentNode.ChildNodes.Add(nodeFile);
        }
    }

代码完整且重新运行,只需更改桌面路径即可。

1 个答案:

答案 0 :(得分:2)

为什么不首先添加Root节点,而是将所有直接后代设置为1级节点:

TreeView TreeView1 = new TreeView();
protected void Page_Load(object sender, EventArgs e)
{
    BuildTree(@"C:\temp");
    form1.Controls.Add(TreeView1);
}
private void BuildTree(string root)
{
    DirectoryInfo rootDir = new DirectoryInfo(root);
    TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
    TraverseTree(rootDir, TreeView1.Nodes);
}
private void TraverseTree(DirectoryInfo currentDir, TreeNodeCollection nodeCollection)
{
    foreach (DirectoryInfo dir in currentDir.GetDirectories())
    {
        TreeNode node = new TreeNode(dir.Name, dir.FullName);
        nodeCollection.Add(node);                
        TraverseTree(dir, node.ChildNodes);
    }
    foreach (FileInfo file in currentDir.GetFiles())
    {
        TreeNode nodeFile = new TreeNode(file.Name, file.FullName);
        nodeCollection.Add(nodeFile);
    }
}

编辑:我修改了上面的代码,删除了我编写的AddToNode方法。前一个方法是检查传入的currentNode对象是否为null,如果是,则将其添加到TreeView1的NodesCollection(否则添加到currentNode的ChildNodes集合)。相反,我不是传递节点,而是传递节点的NodeCollection - 这意味着我们可以简化逻辑。)