Friday, 4 January 2013

TreeView and XmlDataSource Binding in asp.net using C#


Step 1) Create a Empty Asp.net website using C# 4.0/4.5
Step 2) Add a new Webpage, name it as default.aspx
Step 3) Add Xml file called Books.xml

<?xml version="1.0" encoding="utf-8" ?>

<bookslist>
  <book id="ISBN-220-244">
    <title>LINQ Unleased</title>
    <price>$40.99</price>
    <authors>
      <author>
        <firstname>Kimmel </firstname>
        <lastname>Paul</lastname>
      </author>
    </authors>
    <publisher>Sams</publisher>
  </book>
  <book id="ISBN-456-344">
    <title>C# Design Patterns</title>
    <price>$30.99</price>
    <authors>
      <author>
        <firstname>john</firstname>
        <lastname>peter</lastname>
      </author>
      <author>
        <firstname>mary</firstname>
        <lastname>kurl</lastname>
      </author>
    </authors>
    <publisher>Tata Mcgraw Hill</publisher>
  </book>
  <book id="ISBN-434-233">
    <title>Pro Entity Framework 4.0</title>
    <price>29.99</price>
    <authors>
      <author>
        <firstname>Scott</firstname>
        <lastname>Klein</lastname>
      </author>
    </authors>
    <publisher>APress</publisher>
  </book>
  <book id="ISBN-433-234">
    <title>Beginning PHP and MySQL E-Commerce</title>
    <price>$35.99</price>
    <authors>
      <author>
        <firstname>Cristian</firstname>
        <lastname>Darie</lastname>
      </author>
      <author>
        <firstname>Emilian</firstname>
        <lastname>Balanescu</lastname>
      </author>
    </authors>
    <publisher>APress</publisher>
  </book>
</bookslist>


Step 4) Add Treeview and XmlDataSource to aspx page

  XMLDataSource datafile should be books.xml(step3) and xpath should be //book or /bookslist/book

<asp:TreeView ID="TreeView1"  runat="server" DataSourceID="XmlDataSource1" LineImagesFolder="~/TreeLineImages" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" ShowLines="True" ExpandDepth="0" >        </asp:TreeView>

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/data/Books.xml" XPath="//book"></asp:XmlDataSource>
//Datafile Located in data directory
//Bind XMLDataSource to TreeView using XMLDataSourceID.

Step 5) Add Event Handler for OnSelectedNodeChanged

        protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            try
            {
              //This logic helps to get details about selected node.

  
                TreeNode node = TreeView1.SelectedNode;
               String str= TreeView1.DataSourceID;
               XmlDataSource xs = (XmlDataSource)FindControl(str);
                //TreeView1.DataSource will always return null. so FindControl will return 

               //XMLDataSource
 
                XmlDocument doc = xs.GetXmlDocument();
                XPathNavigator nav = doc.CreateNavigator();
                TreeNode parent=node.Parent;
                XPathNodeIterator itr = nav.Select(node.DataPath);
                  
              
                while (itr.MoveNext())
                {
                    Label1.Text=String.Empty;
                     XPathNodeIterator subitr = itr.Current.SelectDescendants(

XPathNodeType.Element, false);
                     if (subitr.Count == 0) //clicked on left node

Label1.Text = itr.Current.Name + ":" + itr.Current.Value;
                    while (subitr.MoveNext()) //clicked on book/authors node
                    {
                       
                            Label1.Text += "<strong>" + 

subitr.Current.Name + "</strong>:" + subitr.Current.Value + "<br/>";
                    }
                }
            }
            catch (Exception ex)
            {
                Page.ErrorPage = "~/Error.aspx?err="+ex.Message;
                Server.Transfer(Page.ErrorPage);
            }
          
        }

Step 6) Run the Webpage default.aspx

Step 7) Click on ISBN-XXXX-XXX book details will be displayed in Label


















Complete Source Code

TreeView_Demo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeView-Demo1.aspx.cs" Inherits="WebApplication1.TreeView_Demo1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        h1
        {
            background-color:navy;
            color:white;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
         <h1>TreeView &amp;XML DataSource Binding in asp.net</h1>
        <table>
            <tr>
                <td style="vertical-align:top">

        <asp:TreeView ID="TreeView1"  runat="server" DataSourceID="XmlDataSource1" LineImagesFolder="~/TreeLineImages"
            OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"
            ShowLines="True" ExpandDepth="0"
            >
            <DataBindings>
                <asp:TreeNodeBinding DataMember="book"   Depth="0"  ValueField="ID"/>
                <asp:TreeNodeBinding DataMember="title"   Depth="1"       TextField="#InnerText"/>
                <asp:TreeNodeBinding DataMember="book"  Depth="1"    TextField="price" FormatString="{0:C}" />
                <asp:TreeNodeBinding DataMember="book"  Depth="2"    TextField="firstname" />
                <asp:TreeNodeBinding DataMember="book"  Depth="2"  TextField="lastname" />
                <asp:TreeNodeBinding DataMember="book" Depth="1"    TextField="publisher" />
               
            </DataBindings>
        </asp:TreeView>
                           

                </td>
                <td style="vertical-align:top">
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
                        <ContentTemplate>

                     <asp:Label ID="Label1" runat="server" Text="Label" Font-Size="Larger" Width="500px" Height="300px" BackColor="teal" ForeColor="white"></asp:Label>
                                                    </ContentTemplate>
                    </asp:UpdatePanel>

                </td>
            </tr>
        </table>
  
      
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/data/Books.xml" XPath="//book"></asp:XmlDataSource>
    </div>
    </form>
</body>
</html>

TreeView_Demo.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
namespace WebApplication1
{
    public partial class TreeView_Demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            try
            {
               
                TreeNode node = TreeView1.SelectedNode;
               String str= TreeView1.DataSourceID;
               XmlDataSource xs = (XmlDataSource)FindControl(str);
               
                XmlDocument doc = xs.GetXmlDocument();
                XPathNavigator nav = doc.CreateNavigator();
                TreeNode parent=node.Parent;
                XPathNodeIterator itr = nav.Select(node.DataPath);
                  
              
                while (itr.MoveNext())
                {
                    Label1.Text=String.Empty;
                     XPathNodeIterator subitr = itr.Current.SelectDescendants(XPathNodeType.Element, false);
                     if (subitr.Count == 0) Label1.Text = itr.Current.Name + ":" + itr.Current.Value;
                    while (subitr.MoveNext())
                    {
                       
                            Label1.Text += "<strong>" + subitr.Current.Name + "</strong>:" + subitr.Current.Value + "<br/>";
                    }
                }
            }
            catch (Exception ex)
            {
                Page.ErrorPage = "~/Error.aspx?err="+ex.Message;
                Server.Transfer(Page.ErrorPage);
            }
          
        }

    }
}

No comments:

Post a Comment