Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » Using XSL and .NET To Display Database Tables in your Web Browser

Using XSL and .NET To Display Database Tables in your Web Browser

This article describes how you can leverage .NET and XSL as a powerful and flexible means to rendering database reports into your Web Browser.

Author Rank:
Total page views :  14125
Total downloads :  348
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DataSetToHTML.zip
 
Become a Sponsor

Figure 1a - DataBound Customer NorthWind Table in a Windows Form

 

Figure 1b - Table Shown in Web Browser

Introduction

I'm currently working on a project that uses XSL (EXtensible Stylesheet Language) to create reports from data by transforming XML into HTML.  I've decided this route is the way to go if you really want the flexibility you need to generate reports and tailor them easily to your needs.  Admittedly, XPath and XSL provide an additional learning curve, but once you get the hang of it, there is no substitute.  You would not find the reporting flexibility, for example, in Crystal Reports or other reporting tools.

In this article we'll show you how to transform any table inside of a dataset into an HTML table and display it in the browser.

The Code

The code for getting our customer table in the database into a table in the browser is fairly straightforward and involves 4 easy steps.

1) Fill a DataSet From the Database

2) Write the DataSet as a DiffGram to XML

3)  Transform the XML to HTML using XSL.

4) Display the HTML in a browser

Because of .NET's well designed architecture, there are almost as many lines of code as there are steps to performing this operation as seen in Listing 1:

Listing 1 - C# Code for Transforming a DataSet into HTML

// 1) Fill the DataSet with the Customer Data from the NWind Database
this.customersTableAdapter.Fill(this.fPNWINDDataSet.Customers);

// 2) Write the XML data for the customer as a diffgram to an xml file
this.fPNWINDDataSet.Customers.WriteXml(@"customer.xml", XmlWriteMode.DiffGram);

XmlDocument doc = new XmlDocument();

// 3) load the customer table into an xmldocument and perform an XSL transform
doc.Load(
@"customer.xml");

XmlWriter writer = XmlWriter.Create(@"customertable.html");
XslTransform transform = new XslTransform();
// load the xslt file used for transformation

transform.Load(@"../../GenerateCustomerReport.xslt");

// transform the customer data in the xml document using the transform
transform.Transform(doc.CreateNavigator(),
null, writer);
writer.Close();

// 4) Display the table in the browser
Process.Start(@"customertable.html");

So the hard part of creating a table in the browser from a database table is not actually the C# coding.  The difficult part is writing the XSL that will generate the table.  When you are designing your reports you will find yourself spending most of your time playing with XSL rather than C#.  The nice part about designing the report using XSL is that you can test and debug against your Xml file directly inside of Visual Studio without having to recompile any C#.

Designing the Table

The first step in creating your report is to open up a pure HTML editor such as Front Page and visually design how you want your table to look.  I've created a simple table shown below with a cool whitestone background for the header:

Figure 2 - HTML Table Design in Front Page

Now copy the source of the HTML into your blank XSL Transform File.  You'll probably need to play with the paths after you add it to your code, but the html tags will be correct.

Listing 2 - HTML Shell of your Table

<html>
<head>
<meta
http-equiv="Content-Language" content="en-us">
<meta
http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>
New Page 1</title>
</head>
 

<body>
<table border="1" width="100%" id="table1" cellspacing="1" cellpadding="0">
   
<tr>
       
<td background="stone.jpg" width="199"></td>
       
<td background="stone.jpg">&nbsp;</td>
       
<td background="stone.jpg">&nbsp;</td>
   
</tr>
  
  <tr>
       <td width="199" bgcolor="#CCFFFF">&nbsp;</td>
            <td bgcolor="#CCFFFF">&nbsp;</td>
            <td bgcolor="#CCFFFF">&nbsp;</td>
      </tr>
      <tr>
            <td width="199" bgcolor="#CCFFFF">&nbsp;</td>
            <td bgcolor="#CCFFFF">&nbsp;</td>
            <td bgcolor="#CCFFFF">&nbsp;</td>
      </tr>
      <tr>
 
          <td width="199" bgcolor="#CCFFFF">&nbsp;</td>
           <td bgcolor="#CCFFFF">&nbsp;</td>
           <td bgcolor="#CCFFFF">&nbsp;</td>
      </tr>

</table>

</body>
</html>

Now we have the a basic shell for creating our XSL Transform markup around the HTML markup.  All we need to do is substitute the xsl and xpath expressions in the places we need to fill in the html table from the DataSet as shown in listing 3:

Listing 3 - XSL for producing an HTML table from the Diffgram

<?xml version="1.0" encoding="UTF-8" ?>
<
xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

      <!--
variable for substituting spaces -->
      <
xsl:variable name="SPC" select="'&#x20;'" />

      <!--
main template for generating html table-->
      <
xsl:template match="/">
      <
html>
         <
head>
           <
meta http-equiv="Content-Language" content="en-us" />
           <
meta http-equiv="Content-Type" content="text/html;
                   charset=windows-1252
" />

           <
title>
            <!--
get the name of the report from the table name-->
            <
xsl:value-of select="name(current()/*/*/*[1])" />
           
 Report
           </
title>

         </
head>
         <
body>
           <
table border="1" width="100%" id="table1" cellspacing="1" cellpadding="0">
             <
tr>

              <!--
loop through the first row and get the column names -->
               <
xsl:for-each select="current()/*/*/*[1]/*">                                   
               <
td background="stone.jpg" width="199">
                 <
B>
                  <
xsl:value-of select="name()" />
                 </
B>
               </
td>
              </
xsl:for-each>                                      
             </
tr>

             <!--
loop through each row and get the row data -->
             <
xsl:for-each select="current()/*/*/*">
               <
tr>
                  <!--
loop through each column in the row -->
                  <!--
and get the data in the cell -->
                  <
xsl:for-each select="current()/*">
                      <
td bgcolor="#CCFFFF">
                        <
xsl:value-of select="." />
                      </
td>
                   </
xsl:for-each>
               </
tr>
             </
xsl:for-each>
           </
table>
         </
body>
       </
html>
    </
xsl:template>
</
xsl:stylesheet>

In order to understand why we used the XPath expressions shown in listing 2 of the XSL we need to look at the diffgram we generate from the dataset.  A diffgram is an XML representation of the DataSet.  In our example we are only exporting the Customer table, so we only need to write XSL for a single table.  Each row of the Customers table inside of the diffgram is grouped directly under the NorthWind DataSet.  All the nodes under the Customers row contain the actual column name and data for that particular row.  Knowing the structure of the XML data we want to transform to HTML gives us an idea of the XSL we need to write. 

Listing 4 - Part of the XML Diffgram of the Customer Table

<?xml version="1.0" standalone="yes"?>
<
diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<
FPNWINDDataSet xmlns="http://tempuri.org/FPNWINDDataSet.xsd">
  <
Customers diffgr:id="Customers1" msdata:rowOrder="0">
    <
CustomerID>ALFKI</CustomerID>
    <
CompanyName>Alfreds Futterkiste</CompanyName>
    <
ContactName>Maria Anders</ContactName>
    <
ContactTitle>Sales Representative</ContactTitle>
    <
Address>Obere Str. 57</Address>
    <
City>Berlin</City>
    <
PostalCode>12209</PostalCode>
    <
Country>Germany</Country>
    <
Phone>030-0074321</Phone>
    <
Fax>030-0076545</Fax>
  
</Customers>
   <
Customers diffgr:id="Customers2" msdata:rowOrder="1">
     <
CustomerID>ANATR</CustomerID>
     <
CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
     <
ContactName>Ana Trujillo</ContactName>
     <
ContactTitle>Owner</ContactTitle>
     <
Address>Avda. de la Constitucin 2222</Address>
     <
City>Mxico D.F.</City>
     <
PostalCode>05021</PostalCode>
     <
Country>Mexico</Country>
     <
Phone>(5) 555-4729</Phone>
     <
Fax>(5) 555-3745</Fax>
  </
Customers>

First of all, we want to write a header row with all the column names.  Since all Customer nodes contain the column names in their column nodes, we just need to get the first row and strip out all the column tag names. The following XSL loop let's us cycle through the columns in the first row.  It selects the XPath expression representing the nodes inside the first Customer Row.
 

     <xsl:for-each select="current()/*/*/*[1]/*">     


Then we can use the  xsl  name function to pick out each tags name to get us the name of the column.
 

     <xsl:value-of select="name()" />

The next step is to populate the actual data for every row.  To loop through the rows of the data table, we'll use the following for-each xsl/xpath expression.  This XPath expression selects each Customers node in the diffgram

             <!-- loop through each row and get the row data -->
             <
xsl:for-each select="current()/*/*/*">

Now we need to loop through each column containing the data.  So we'll have another loop that uses xpath to pick each child node out of the current Customers Node:

<!-- loop through each column in the row -->
<!--
and get the data in the cell -->
<
xsl:for-each select="current()/*">

Finally we need to pull the data out of each Column Node that we are looping through and place them into the HTML <td> tag using XSL value-of the current column data.  (A period(.) represents the current node you are on inside the transform)

<td bgcolor="#CCFFFF">
<
xsl:value-of select="." />
</
td>

Conclusion

With the power of XSL, you can bend XML data to your will and render it to a browser.  As with any other new language XSL and XPATH, take a bit of time to get the hang of, but once you've used it in one or two reports, there is no turning back.  .NET  gives you the added power of passing parameters from C# directly to your XSL Transform, so you can easily have your C# Code interact with your reports through button presses and checkboxes.  Anyway,  now that I have finished reporting to you about the power to transform your life using C# .NET and XSL, hopefully it will benefit you in your work.


Login to add your contents and source code to this article
 Article Extensions
Contents added by yinsu kolay on May 15, 2009
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DataSetToHTML.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
program by Mohd On February 9, 2008
programing to design a pyramid using in c#
Reply | Email | Delete | Modify | 
program by Mohd On February 9, 2008
to design a program of binary search tree in recursive method using c#
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.