Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » ASP.NET » Displaying single table database hierarchy with DataSet and DataRelations

Displaying single table database hierarchy with DataSet and DataRelations

Hierarchies can be difficult to store SQL tables and even more difficult to query and display. This Example will show you how you can use DataRelation to convert single table hierarchy in to nested XML and then use XSLT to transform it to nested list.

Author Rank :
Page Views : 13906
Downloads : 186
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
hierarchy.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Hierarchies can be difficult to store SQL tables and even more difficult to query and display. This example will show you how you can use DataRelation to convert single table hierarchy in to nested XML and then use XSLT to transform it to nested list.

DataRelation is one of the least talked about feature of dataset, it can do wonders if you know how use it in your advantage. It can generate parent child display with nested repeater or even cross tab display if you know how to play with dataset and relations correctly.

Let's dive into details of how you can create nested xml and display on ASP.Net web page. To start with we will select our data table which has hierarchical data.

Table structure and data.

There are several methods to store hierarchy in database but most famous ones are "Adjacency Model" and "Nested Set Model", we will use "Adjacency Model" for our sample, we are going to use Employee table from NorthWind database, following is the structure of table. ReportsTo column has ID of Employee to which Employee reports.

 Employee Table Structure

And following is data inside employee table our goal is to convert that data into nested XML data which we can use in our ASP page to display hierarchy.

 Employee Data

Getting DataSet and adding relation.

We will get four columns from the employee table (EmployeeID, FirstName, Title and ReportsTo). Once we have dataset filled with data we will add relation to that dataset.

Following code retrives dataset and adds DataRelation

DataSet result = new DataSet();

string connString = "server=localhost;Trusted_Connection=true;database=northwind";

using (SqlConnection myConnection = new SqlConnection(connString))

          {

                   string query

                             = "Select EmployeeID,FirstName,Title,ReportsTo from Employees";

                   SqlCommand myCommand = new SqlCommand(query,myConnection);

                   SqlDataAdapter myAdapter = new SqlDataAdapter();

                   myCommand.CommandType = CommandType.Text;

                   myAdapter.SelectCommand = myCommand;

                   myAdapter.Fill(result);

                   myAdapter.Dispose();

          }

result.DataSetName = "Employees";

result.Tables[0].TableName = "Employee";

DataRelation relation = new DataRelation("ParentChild",

result.Tables["Employee"].Columns["EmployeeID"],

result.Tables["Employee"].Columns["ReportsTo"],

true);

relation.Nested = true;

result.Relations.Add(relation);

You must be familiar with first part of the code which retrieves dataset using DataAdapter, once we have data set we will name dataset and datatable so that xml output has proper element name instead of default "DataSet" and "Table1" as element, next part is most important for us, we will set DataRelation in that part.

We will use DataRelation constructor which takes four parameters. First parameter is name of relation, second parameter is parentColumn which in our case is "EmployeeID" column and third parameter is child Column which in our case is "ReportsTo" and last one is createConstraints we will set it to true because we know all data is valid in our table.

And then we will set Nested property to true so that dataset can create nested XML for us.

Generated XML

We will use DataSet.GetXml() method to generate XML out of dataset, following is the structure of XML generated by dataset. As you can see employeeid 1 is child of employeeid 2.

<Employees>

  <Employee>

    <EmployeeID>2</EmployeeID>

    <FirstName>Andrew</FirstName>

    <Title>Vice President, Sales</Title>

    <Employee>

      <EmployeeID>1</EmployeeID>

      <FirstName>Nancy</FirstName>

      <Title>Sales Representative</Title>

      <ReportsTo>2</ReportsTo>

    </Employee>

    ...

  </Employee>

</Employees> 

Transforming XML using XSLT

XSL Transformation is one of the best option if you want to display nested data, actually before Sitemap and TreeControl which came with ASP.Net 2.0 XSL transformation was the only neat way to display hierarchy.

We will use System.Web.UI.WebControl.Xml control to display xml content using XSL Transformation. Xml control requires XmlDocument and Transformsource to transform the document.

Following is the XSLT that we will apply to XML document. XSLT will perform recursive transformation to generate nested list.

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

<xsl:stylesheet version="1.0"

  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output omit-xml-declaration="yes" />

  <xsl:template match="/Employees">

    <xsl:call-template name="EmployeeListing" />

  </xsl:template>

  <xsl:template name="EmployeeListing">

    <ul>

      <xsl:apply-templates select="Employee" />

    </ul>

  </xsl:template>

  <xsl:template match="Employee">

    <li>

      <xsl:value-of select="FirstName"/>

      <xsl:if test="count(Employee) > 0">

        <xsl:call-template name="EmployeeListing" />

      </xsl:if>

    </li>

  </xsl:template>

</xsl:stylesheet>

Following is the final result.

 Result of Transformation

End notes

This sample displays nested list, but you can use same principle to display tree structure, site menu and many other hierarchal data. A part that I have not touched in this sample is retrieving data only under certain node, but you will be able to find methods of doing that by searching on internet. Also take a look Joe Celko's favorite Nested Set model for storing hierarchy in SQL.

Run sample code

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Jigar Desai
Jigar Desai is a Microsoft certified professional and has 8 years of experience in Microsoft technologies, he is working in asp.net since pre beta releases and has extensive experience in developing database driven web application. When he is not working with asp.net and SqlServer he likes to do experiments with GDI+ and Content automation in webapplications.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
interesante by william On January 24, 2012
sigan publicando, para revisar. saludos will
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.