BizTalk Utilities CV ,   Jobs ,   Code library  
 
Home Page
.NET and XML
Handling Events
Data with a TreeView
ASP.NET XML Architecture
Code to create entire file system as XML File in VB.NET
Class object for Base64 conversion with .NET
XML Web Services and ASP.NET
String Handling Application using ASP.NET
XML Serialization and .Net
Dynamic Method Invocation in .NET using Reflection API
Using XML classes in .Net
Pass node sets to XSLT stylesheets using .NET
Output a directory as XML using .NET
.Net, COM Interoperability and Word Object Model
WS-Routing for .NET endpoints
Using XML and XSLT in VB.NET Jeopardy
Symmetric Encryption/Decryption with .NET
XInclude.NET 1.0
EXSLT.NET 1.0
How to read a XML file using XmlTextReader?
How to compare a XML element with XmlTextReader?
<< XSLT
 

By :Mark Wilson
I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :03/24/2008
Times viewed :1223

 

Populating a TreeView Control

We are going to examine a number of different techniques to populate a TreeView web control from XML data in this section. At first we are going to build the entire tree programmatically. This does not require any XML but it helps `to understand the inner workings of the TreeView better. Next we will learn how to bind XML data automatically, which saves us some code writing but takes away some of the flexibility we have when we set up the tree in code. Finally we will take a look at a combination of the two techniques to improve performance of a TreeView by populating only the visible nodes of the tree. All examples in this section are different versions of the same ASP.NET page that displays an order-order detail hierarchy. This page is part of a two page frameset, similar to the set up of the MSDN library. The left frame presents the TreeView to select the item to display in the right frame ( see figure XX ). The right frame shows the details about the ordered product using the page from the example in figure 17.7.

Programmatic Population of a TreeView Control

Before we can populate a Tree View tree we need to create an ASP.NET page with a blank Tree View Web Control on it. If you are using a graphical design tool like Visual Studio.NET or Web Matrix, you can add the Tree View to the toolbox, create a new Web Form and simply drag and drop the Tree View onto your page with the Web Forms Designer. Otherwise you add the treeview tag to the ASP.NET page as shown in the page below.

<%@ Page language="c#" Codebehind="OrderTree.aspx.cs"

  AutoEventWireup="false" Inherits="SouthRain.WebForm1" %>

<%@ Register TagPrefix="iewc"

    Namespace="Microsoft.Web.UI.WebControls"

    Assembly="Microsoft.Web.UI.WebControls, Version=1.0.2.226,

    Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<HTML>

  <body>

    <form id=Form1 method=post runat="server">

      <iewc:treeview id=TreeViewOrders style="Z-INDEX: 101; LEFT: 7px;

        POSITION: absolute; TOP: 29px" runat="server" Width="350px"

        Height="600px" />

    </form>

  </body>

</HTML>

You can tell from the Page directive that this example makes use of the code-behind feature (which is not available in Web Matrix) where we write page code in a separate file that is pre-compiled into a .NET assembly. The Page directive links the page file to the code-behind page named OrderTree.aspx.cs. The Register directive declares the WebControls library to this ASP.NET page and defines that tags with the namespace prefix iewc identify web controls from that library.

NOTE: The Assembly declaration on the Register directive is only valid for the page at run-time. You still need to add a project reference to the Web Controls assembly if you set up a code-behind page.

Now we have a Tree View where we can add nodes to the tree. It is very straight-forward to add them programmatically. The Tree View control maps to a field of type TreeView in the code-behind file, where we can write code against it.


Figure 17.9: Tags in the aspx page map to fields in the class in the code-behind file.


The TreeView class exposes a Nodes property of type TreeNodeCollection. This collection acts as the root of the hierarchy of the nodes in the Tree View. We can build the first level of the tree by adding a TreeNode object to the Nodes collection for every top-level node in the tree. The TreeNode class itself also exposes a Nodes property to create subsequent levels in the noew hierarchy. The TreeView and the TreeNode classes also expose several properties to customize the appearance and the behavior of the tree and of individual nodes. We can define if an individual node is expandable, if it is initially expanded and if it acts as a hyperlink, just to name a few of the available options.

The next code sample shows pieces from the code-behind file for the page file above. The FillTree() method demonstrates populating a Tree View from an XML document with a simple parent-child hierarchy. The if statement in the Page_Load method makes sure that we populate the tree view only once from the database. If the page reloads because of a user event IsPostBack is set to true and the TreeView refreshes from the View State rather than calling FillTree() again.

using System;

using System.Xml;

using CompleteXml.SouthWind.Managers;

public class TreePage : System.Web.UI.Page

{

  protected Microsoft.Web.UI.WebControls.TreeView TreeViewOrders; | #1

  private void Page_Load(object sender, System.EventArgs e)

  {

    if( false == this.IsPostBack )              | #2

    {                                           |

      FillTree();                               |

    }                                           |

  }

  private void FillTree( string xmlOrders )

  {

    OrderManager om = new OrderManager();

    XmlDocument doc = new XmlDocument();

    doc.LoadXml( om.GetAllFullOrders() );

    TreeNode orderNode;

    TreeNode orderItemNode;

    foreach( XmlNode node in doc.SelectNodes("Orders/FullOrder" ) )

    {

      orderNode = new TreeNode();                          | #3

      orderNode.Text = String.Format("Order {0}",         |
        node.SelectSingleNode("OrderID").InnerText );      |

      TreeViewOrders.Nodes.Add( orderNode );               | 

     

      foreach( XmlNode itemNode in node.SelectNodes(
        "OrderItems/OrderItem" ) )

      {

        string productId = itemNode.SelectSingleNode(

          "ProductID" ).InnerText;

        orderItemNode = new TreeNode();

        orderItemNode.Text = String.Format("Product {0}", productId );

        orderItemNode.NavigateUrl = String.Format(
          "ProductPage.aspx?ID={0}", productId );

        orderItemNode.Target = "main";

        orderNode.Nodes.Add( orderItemNode );

      }

    }

  }

…  |#4

[Md1]

 }

(annotation) <#1 We need to define a field with the same name as the id of treeview tag on the page template to access it in the code-behind page.>

(annotation) <#2 ASP.NET calls the Page_Load method every time it processes the page. The first time the user requests this page in a viewing session we initialize the TreeView from the database. If we re-initialize the page because of a user event the tree is populated from the ViewState.>

(annotation) <#3 Create a new node object, set the properties to define the node’s behavior and add it to its parent node.>

(annotation) <#4 We omitted some wizard generated code for the page initialization.>

Now we have seen what the rendered tree looks like, we have seen what the ASP.NET page and the code look like that rendered the tree. What we have not seen is what is actually going on when a browser requests the page. The Tree View Web Control serializes the TreeViewNodes collection into special tags in the generated HTML page. A (somewhat simplified) HTML page with a one-node Tree View could look like this example. The real output contains more attributes on the treeview and tree node elements that customize the Tree View’s appearance, but they are not important right now.

<html>

  <body>

    <tvns:treeview id="TreeViewOrders" selectedNodeIndex="0" >

      <tvns:treenode Expandable="checkOnce" Selected="true">

                        Order 10248

      </tvns:treenode>

    </tvns:treeview>

  </body>

</html>

When Internet Explorer receives this page it renders the treeview and treenode tags using JavaScript and a set of images that the Web Controls installer installed on your web server. If you programmed complex client-side JavaScript effects you can imagine that parsing the <treenode> tags on the client can get somewhat sluggish for clients running a computer with a slower processor (like the one your kids gave back to you because their games don’t run fast enough). Therefore it is important to limit the number of nodes you are sending back to the browser. Fewer nodes mean not only faster transmissions, but also much faster rendering. Section 17.XX will demonstrate a technique that is very useful in that respect.

This concludes the section on populating a Tree View node-by-node. This technique is not specific to an XmlDocument but it’s a very common solution. Alternatively, you may want to consider parsing XML with an XmlSerializer rather than the XmlDocument to write better readable code and benefit from the stronger typing of the deserialized object hierarchy. You can see the difference if you download the sample application from our web site. It also contains a version of this page built with the XmlSerializer.


Rate this article on a scale of 1 to 10

Your vote :  


 

Recent Jobs

Sr. Software Engineer - Analytics
Immediate Mainframe openings for Ch
Immediate TANDEM-TAL openings for C
Immediate ASP.NET/C# Openings for C
Sr. Software Engineer

View all Jobs (Add yours)
View all CV (Add yours)



swimming pool contractor
conference call
water softener
Teleconference
Host Department NOLIMIT Web Hosting
MSN
sunglasses
help desk support


    Email TopXML  

Front Page Daily Stuff TopXML Forum XML blogs XML Newsgroups BizTalk Biztalk Utilities Biztalk Utilities Tutorial B2B SAP XML Microsoft .NET Dotnet System XML Soapformatter SQLXML XMLserializer XQuery PHP PHP SimpleXML PHP XML Dom PHP XML RPC PHP XSLT Java Java Java XML Xalan Microsoft ASP ASP Schemas XML SQL Server XML XMLDom XSL XSL Tutorial XSLT Stylesheets General Javascript CSS XHTML WAP