0

I am populating a TreeView control's nodes at the moment user expands the parent node - the first time - using populate on demand as described in ASP.NET: How to Create an Expandable Empty TreeNode. The population process works fine.

The problem is when I try to get the TreeNode.Parent I get a null even if the TreeNode was not a root node. Also, TreeNode.ChildNodes returns an empty collection even if there were some child nodes for the specified TreeNode ...

Is there an explanation for this? And, what can I do to solve it ?

Thank you.

Community
  • 1
  • 1
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65

1 Answers1

0

If your user has selected the root parent node, this code example below should work to populate the tree using a collection of data:

protected void ParseTreeNodes(object sender, System.Web.UI.WebControls.TreeNodeEventArgs e)

{
    //Uncomment this line below and inspect the 'nodes' variable if you need to inspect all of the nodes
    //var nodes = this.MyTreeView.Nodes;

    //Some call to get data for example
    var dataCollection = GetSomeDataForTheTree()

    //Iterate through and create a new node for each row in the query results.
    //Notice that the query results are stored in the table of the DataSet.
    foreach (MyClassWithData data in dataCollection)
    {
        //Create the new node using the values from the collection:
        TreeNode newNode = new TreeNode(data.LastName, system.ID)
            {
                //Set the PopulateOnDemand property to false, because these are leaf nodes 
                and do not need to be populated on subsequent calls.
                PopulateOnDemand = false,
                SelectAction = TreeNodeSelectAction.Select
            };

        //Add the new node to the ChildNodes collection of the parent node.                    
        e.node.ChildNodes.Add(NewNode);
    }
}

I added an additional line of code to inspect the current nodes in the treeview if you are having an issue with the parent node or knowing the specific values in the Nodes collection.

atconway
  • 20,624
  • 30
  • 159
  • 229