开发者

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


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.


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


        }


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

treeView1.TopNode.Expand();


TreeNode rootNode = treeView1.TopNode;

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜