Populating Tree Nodes in the TreeView Web Server Control
The TreeView Web server control can display several different types of data: static data that is specified declaratively in the control; data that is bound to the control; or data that is added to the TreeView control dynamically, in response to user actions.
The simplest data scheme is declarative static data. To display static data by using declarative syntax, create a collection of nodes that are children of the TreeView control.
The following example shows the markup for a TreeView control that contains three nodes, two of which have child nodes.
<asp:TreeView ID="TreeView1" Runat="server"> <Nodes> <asp:TreeNode Value="Parent1" Expanded="True" Text="1"> <asp:TreeNode Value="Child1A" Text="A" /> <asp:TreeNode Value="Child1B" Text="B" /> </asp:TreeNode> <asp:TreeNode Value="Parent2" Text="2"> </asp:TreeNode> <asp:TreeNode Value="Parent3" Expanded="True" Text="3"> <asp:TreeNode Value="Child3A" Text="A"> </asp:TreeNode> </asp:TreeNode> </Nodes> </asp:TreeView>
To display data that is declaratively bound to the control, first add a hierarchical data source control, such as the XmlDataSource control, to the page and assign it an ID. Then, set the DataSourceID property of the TreeView control to the ID of the data source control. The TreeView control can automatically bind to the data source and display its values.
By default, when binding to a data source where each data item contains multiple properties — such as an XML element with several attributes — a node displays the value returned by the ToString method of the data item. In the case of an XML element, the node displays the element name. This schema shows the underlying structure of the tree, but is not very useful otherwise. You can bind a node to a specific data item property by specifying tree-node bindings using the DataBindings collection. The DataBindings collection contains TreeNodeBinding objects that define the relationship between a data item and the node it is binding to. You can specify the criteria for binding and the data item property to display in the node. For more information about tree-node bindings, see TreeNodeBinding.
It might not be practical to define your data structure statically, or the data might depend on information that you gather at run time. You can populate TreeNode objects in a TreeViewcontrol's Nodes collection programmatically from server-side code or you can utilize the PopulateOnDemand feature of the TreeView control to populate nodes dynamically when the parent node is expanded on the client. For more information, see Binding Data to the TreeView Web Server Control.