Hide rootnode in treeview asp.net

六月ゝ 毕业季﹏ 提交于 2019-12-12 02:09:58

问题


How can I hide the rootnode in this case the "temp" folder? I want to do this whitout setting a CssClass on the rootnode.

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);
        }
    }

The code is complete and redy to run just change the path to your desktop.


回答1:


Why not just not add the Root node in the first place, instead, set all the direct descendants as level 1 nodes:

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);
    }
}

Edit: I have amended the code above to remove the AddToNode Method I wrote. The previous method was checking to see if the currentNode object passed in was null, and if so adding it to the NodesCollection of TreeView1 (otherwise to the ChildNodes collection of the currentNode). Instead, rather than passing the node around, I'm passing the NodeCollection of the node around - this means that we can simplify the logic a fair bit).



来源:https://stackoverflow.com/questions/18383391/hide-rootnode-in-treeview-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!