Visual Studio .NET - TreeView Node Selection

Asked By Partha Chakraborty on 21-Feb-08 01:55 AM

I have implemented treeview control in my web page. I have written the following code to select a particular treeitem(node):

private bool SelectNode(TreeView TreeView)

    {

        Int32 i = 0;  

        Int32 SelectedNode = Convert.ToInt32(Request.QueryString["ID"]);

        foreach (TreeNode node in TreeView.Nodes)

        {

            if (SelectedNode == Convert.ToInt32(node.Value))

            {

                TreeView.Nodes[i].Selected = true;

            }

            i++;

        }

        return true;

    }

The Convert.ToInt32(Request.QueryString["ID"]) this statement determine the value of the node. But this statement only the nodes in the root lavel. But there can be n-number of lavels. How can I select the nodes under the root level or any level.

Any idea. Any help will be thankfully received.

 

Partha

check for the childnodes

Shallu Gupta replied to Partha Chakraborty on 21-Feb-08 03:02 AM
    you need to check whether the node has got child nodes or not and loop through each child node.
create another recursive function which takes in treenode as a parameter and checks if node has got child or node and loop through each node. and call that method in your above for loop.
Hope this helps



The easiest way is recursion...

Nenad Prekupec replied to Partha Chakraborty on 21-Feb-08 04:03 AM
return true;the easiest way is to that through recursion method like that:

private bool SelectNode(TreeNodeCollection nodes, int id)

    {

       if (nodes.count == 0)

          return false;


        Int32 i = 0;  

        foreach (TreeNode node in nodes)

        {

            if (id == Convert.ToInt32(node.Value))

            {

                TreeView.Nodes[i].Selected = true;

                return true;

            }

            else

            {

                if (SelectNode(TreeView.Nodes[i].ChildNodes, id))

                   return true;

            }

            i++;

        }

        return true;

    }

and call like:

SelectNode(TreeView.Nodes,  Convert.ToInt32(Request.QueryString["ID"]));

this will go through all nodes of the tree and select the proper one and return true if that one exist.