LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8826

How do you get the root node or the first level node of the selected node in a tree view?

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

Upvotes: 11

Views: 60703

Answers (4)

Olga Ivolgin
Olga Ivolgin

Reputation: 11

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


        }

Upvotes: 0

Chathura Liyanage
Chathura Liyanage

Reputation: 320

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

treeView1.TopNode.Expand();

Upvotes: -1

Jebu
Jebu

Reputation: 385

TreeNode rootNode = treeView1.TopNode;

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

Upvotes: -9

digEmAll
digEmAll

Reputation: 57220

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.

Upvotes: 35

Related Questions