11

Are there more straight forward method than the code below to get the root nodes or the first level nodes in a tree view?

TreeNode node = treeView.SelectedNode;

while(node != null)
{
       node = node.Parent;
}    
LEMUEL ADANE
  • 6,680
  • 14
  • 48
  • 64
  • In my programs, I do it just as you described (or at least similar; your code would always lead to a `null` reference in the `node` variable). Do you experience performance issues with this? – Uwe Keim Dec 23 '10 at 16:20
  • 3
    @Vlad Lazarenko This would only work if you have just one single root node. – Uwe Keim Dec 23 '10 at 16:31

4 Answers4

33

Actually the correct code is:

TreeNode node = treeView.SelectedNode;
while (node.Parent != null)
{
    node = node.Parent;
} 

otherwise you will always get node = null at the end of the loop.

BTW, if you are sure to have one and one only root in your TreeView, you could consider to use directly treeView.Nodes[0], because in that case it would give the root.

digEmAll
  • 53,114
  • 9
  • 109
  • 131
0

Try This. It's Worked for me...!

treeView1.TopNode.Expand();
  • 1
    Did you read the question? See the downvoted answer in regards to the TopNode issue. – LarsTech Jan 19 '17 at 03:52
  • That command alters the display of the treeview. Showing expanding the node. The question (IMHO) was aking how to get the root node, of the selected node, as an object in code. – TinyRacoon Jul 15 '19 at 16:03
0
protected void Submit(object sender, EventArgs e)
        {
           ///naidi root 

            string name = Request.Form["Name"];
            if (String.IsNullOrEmpty(name))
                return;

            if (TreeView1.Nodes.Count <= 1)
            {
                System.Web.UI.WebControls.TreeNode newNode = new TreeNode("Porposal");
                TreeView1.Nodes.Add(newNode);
            }




            System.Web.UI.WebControls.TreeNode newNode1 = new TreeNode(name);
            TreeView1.Nodes[1].ChildNodes.Add(newNode1);


        }
Irshad
  • 2,860
  • 5
  • 25
  • 45
  • It's not really clear how this answers the question and the code in the comment doesn't help. You need to edit your question. – Karl Richter Feb 10 '18 at 19:36
-8
TreeNode rootNode = treeView1.TopNode;

this should be all you need. SelectedNode doesn't need to be always != null

Jens Busch
  • 335
  • 3
  • 5
  • 4
    This is horrifically wrong. This gets the "first fully-visible tree node in the tree view control.". Note that "Initially, the TopNode returns the first root tree node, which is located at the top of the TreeView. However, if the user has scrolled the contents, another tree node might be at the top.". – woddle Nov 18 '13 at 12:16