Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Reporting Services » Reporting Hierarchical Recursive Data with MS Reporting Services using VB.NET

Reporting Hierarchical Recursive Data with MS Reporting Services using VB.NET

An article to demonstrate Reporting of Hierarchical Recursive Data hosted with Smart Client using MS Reporting Services.

Page Views : 17702
Downloads : 229
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:
RecursiveData.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

 

I will start with a question here. How many of you had chance to interact with Employee table from sample database Northwind? There you go... I can imagine countless hands in air, and why not it is one of the standard databases comes with both Access and SQL server. All right, are we going to discuses Northwind database here? NO. Is Employee table is something special? I would say YES to this. Why special? Well, if you pay a close attention, it is just like any other standard table, however, two fields from the table, "EmployeeID" and "ReportsTo" are related to each other in an interesting way! Yes, you got it right; I am talking about Hierarchical relationship which we also call commonly as Recursive data. I am trying to shade some light on reporting of data which is recursive in nature. 

 

 

 

What is Recursive Data?

 

I am sure you must have come face to face with this challenge called Recursive Data if you have to deal with databases.  Hierarchical data which defines the level of association with a defined relationship ca be called recursive in nature. A typical example would be to take Accounting Application Database which has a table called ChartOfAccounts, the Primary Key "Account_Id" will have foreign key relationship with another column called "Reporting_Account_Id".  Another example is the one which I am using in this article is that each Employee has a Manager assigned.

 


 

Do you recall "Self-Join"? As you can see in above image, this is one way we display the recursive nature of data, just putting here for some better understanding.

 

Reporting Challenge for Recursive Data

 

I am ready with my second question here, before I ask you; I would like your kind attention to the image with Employee level output. Now the question: Do you think generating report like that without any custom code is piece of cake? I am pretty sure this time I will see many less hands in air compare to my first question! Or you can say yes it is piece of cake if you have already tried your hands on MS Reporting Services.

 

It is very common that when we have to deal with a situation like this, we do end up writing some sort of custom code in order to find out the level of hierarchy etc. A typical developer mindset will always have endless list of wishes for software vendors, one of my wish was if something was done to address this issue of handling recursive data built right into the reporting engine.  Some how I felt my telepathy worked and guys at Microsoft put this feature into reporting services and here I am acknowledging them by writing few lines here. Though, I would like to clarify one point here, I have worked with several other reporting engines and did enjoyed them, however, since I started to work with Reporting Services, I personally felt much at ease.

 

Let's wear our Report Writing hat now...

 

When I look at different reporting engines out there in market, the underlying concept remains very much same; I am talking about header, footer, data region, data grouping, summary etc. So, even if you have not yet exposed to reporting services, don't worry if you have working knowledge of any reporting engine, you will not have much difficulty to grasp the concept laid down in this article.

 

With this article I would also like to show the reader how reporting services can be used with smart client windows forms application in a client environment.

 

I assume the reader of this article is comfortable using Visual Studio 2005, VB.NET, Sql Server 2000 and Windows Forms. Article is not at all a "Reporting Services 101", hence I will assume that you will try to play with attached code and figure out secrets hidden with it.

 

Implementing reporting services into smart client is like 1.2.3...

  1. Create a DataSet
  2. Create Report
  3. Use Preview control to generate report with ADO.NET code interface 

1. DataSet at your service

 

In order to create a dataset, just click Add New Item from Solution Explorer. Select DataSet from Visual Studio installed templates and give it a proper name. After Dataset is created, open it in a designer window and add a DataTable to it. After you have added DataTable add required columns to it, in this example I have three columns added, namely, EmployeeName, EmployeeID and Reports_to, please make sure to set the DataType property of each column to String, Int32 and Int32 respectively. 

 

 

The DataSet should typically look like the above image. Now that we have our DataSet ready, you will shortly see a fun way to fill it using a new technique introduced in ADO.NET of using a SqlDataReader to Fill a Dataset (I guess my telepathy worked here too). 

2. Report Design

 


 

As we did with DataSet, just click Add New Item from Solution Explorer. Select Report from Visual Studio installed templates and give it a proper name. As I clarified earlier, I am not going into details for each and every control/elements of Report Designer; instead I will only point you to important location which needs attention in order to create Report which is using recursive data.

 

As you can see in the above image, this is how my reports look like in designer. Typical of report writing tool, reporting services also have interface where you can define header and footer to begin with and move on to report body etc. In the header section I have the Report Title (Magenta color) and Run Date (Blue color).

 

The most interesting part which I felt is the Body section, also called data region. Data region allows you to put several new exiting controls which basically decide how the data will be outputted. I have used "Table" control here which comes with ready header and footer for it when placed on designer surface for first time.

 

TextBox contol is used heavily to display information, if you look at the image you can see that I just placed a textbox control and simply typed the report title inside. When it comes to specify expression, all you have to do is start with "=" sign in front.  You can check the Run Date example, in which I am concatenating string "Run Date" and VB.NET function "Today" to return current date.

 

After putting all the required control on the designer surface and making sure the layout meets out taste, it is time to spell the magic beans which will automatically handle the recursive nature of data and manage hierarchy level etc.

 

The trick is to put the grouping on detail section (make sure to select detail band and right click to access group menu choice), by specifying group on "EmployeeID" and parent group "ReportsTo" as per image mentioned below:

 


 

Report writer has useful inbuilt function like "Level", which returns the current level of depth in a recursive hierarchy.

 

For next output column in report Level, we will specify following expression:

 

=Level("tableEmployee_Details_Group") + 1

 

Level function return integer starting with 0 for fist level; hence I have added a 1 to end result here. So, in our example employee "Andrew Fuller", is topmost level, you can easily use function like Switch() or IIF() to take this level number and substitute with something like "CEO", "General Manager" etc.

 

The third and last column in report displays the count of all the employees who are reporting to given employee record. The following expression does the trick for us:

 

=Count(Fields!EmployeeID.Value, "tableEmployee_Details_Group", Recursive) - 1

 

For both the expression "tableEmployee_Details_Group" is used as reference name to group definition which we applied on detail band of data.

 

Did you also noticed on interesting thing about the Hierarchical formatting of EmployeeName in report output? This is also done fairly easily with following expression which you need to specify in Padding->Left property:

 

=Level("tableEmployee_Details_Group") * 20 & "pt"

 

Based on each incremental level it will add 20 pt to left side of EmployeeName and the output will look like a try structure.

 

3. Show me the Report!

 

I know after going through all that preparation, we are eager to see the output for report, aren't we? Following code will just do that!

 

You can start by putting ToolBox->Data->ReportViewer control on a standard windows form. I am using VB.NET here within windows forms application framework, the same can be manipulated easily for a ASP.NET application framework and further, could can be easily converted to C#.NET if that is what you use as your primary scripting language.

 

Make sure you have the code behind Form Load method as follows:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load

    'declare connection string

    Dim cnString As String = "Data Source=(local);Initial Catalog=northwind;" & "User

    Id=northwind;Password=northwind"

 

    'use following if you use standard security

    'string cnString = @"Data Source=(local);Initial Catalog=northwind;

    'Integrated Security=SSPI";

 

    'declare Connection, command and other related objects

    Dim conReport As SqlConnection = New SqlConnection(cnString)

    Dim cmdReport As SqlCommand = New SqlCommand()

    Dim drReport As SqlDataReader

    Dim dsReport As DataSet = New dsEmployee()

 

    Try

        'open connection

        conReport.Open()

 

        'prepare connection object to get the data through reader and populate into dataset

        cmdReport.CommandType = CommandType.Text

        cmdReport.Connection = conReport

        cmdReport.CommandText = "Select FirstName + ' ' + Lastname AS EmployeeName, EmployeeID, ReportsTo

        From Employees"

 

        'read data from command object

        drReport = cmdReport.ExecuteReader()

 

        'new cool thing with ADO.NET... load data directly from reader to dataset

        dsReport.Tables(0).Load(drReport)

 

        'close reader and connection

        drReport.Close()

        conReport.Close()

 

        'provide local report information to viewer

        reportViewer.LocalReport.ReportEmbeddedResource = "RecursiveData.rptRecursiveData.rdlc"

 

        'prepare report data source

        Dim rds As ReportDataSource = New ReportDataSource()

        rds.Name = "dsEmployee_dtEmployee"

        rds.Value = dsReport.Tables(0)

        reportViewer.LocalReport.DataSources.Add(rds)

 

        'load report viewer

        reportViewer.RefreshReport()

    Catch ex As Exception

        'display generic error message back to user

        MessageBox.Show(ex.Message)

    Finally

        'check if connection is still open then attempt to close it

        If conReport.State = ConnectionState.Open Then

            conReport.Close()

        End If

    End Try

End Sub

My favorite section - About...

 

As, we all know in community, there are always more then one way to address an issue. I am certainly not suggesting this is only way we can handle data which is Recursive in nature. I would love to hear from you if you like to share some of your tricks and looking forward to have any constructive criticism you got for me.

 

Disclaimer: Please feel free to use the content of this Article as you may please, however, I won't be held liable for any adverse effect, if at all it produces.

 

Thanks for reading... till my next attempt. Chao.

 

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/).

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
 
Asif Sayed
Asif Sayed has over fifteen years experience in software development and business process architecture. A senior systems analyst with a leading North American energy and services provider in Toronto, Canada, he also teaches .NET technologies at Centennial College in Scarborough, Ontario. He has a book published by Apress with the Title "Client-Side Reporting with Visual Studio in C#".
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
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:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Need by Mony On April 23, 2007
I just want to pass fews parameters from form1(main form) to form2(report). can you show me please.
Reply | Email | Modify 
Re: Need by Asif On April 24, 2007

Hi,

I am not sure if you looking for passing parameters to report or passing values from one form to another form?

Regards,

Asif

Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.