Dynamic Data Grouping using MS Reporting Services

 
Image: 1.0
 

Introduction

 
We hear this all the time, "Two birds with one stone." What if I say, "Four birds with one stone"? I am sure four sound much better than two. So, what are my four birds and one stone?
 
My four birds are four distinct different outputs generated using source NorthWind->Orders (Sql Server 2000) and my stone is single physical Ms Reporting Services .rdlc file, which I am using as a template to produce different outputs. This particular saying is perfectly applicable to the technique, which I am going to share with you.
 
The application of the technique is not something new; we all have done the same or similar while dealing with reporting of data. What is new here is the approach, which I can call it to reuse of report (as we commonly reuse the code).
 
Let us discuss a practical scenario here. If I ask you, what kind of output you see in (image 1.0); you would probably say a simple report listing orders information. Well, you guessed it rite. What you will do if end-users want the same report using data grouped by CustomerID(image 1.1)? In most cases, perhaps you will end up writing a new report. In this article, I will demonstrate the way you can avoid this and reuse the report to produce different outputs.
 
I assume the reader of this article is comfortable using Visual Studio 2005, C#, SQL Server 2000, and Windows Forms. Basic understanding of how report designer works are helpful to work with the attached code.
 

Three-button technique

 
Now, to make life a little interesting, I added three extra buttons: Orders by Customer, Orders by City, and Orders by Country to the user interface. These three extra buttons on the user interface do not have any built-in magic; they are just helping me demonstrate the technique. So, without keeping you folks into much suspense any further:
 
 
Image: 1.1
 
Remember the game of "spot the difference" from childhood memories? May I ask you to play the same game with Image 1.0 and 1.1? Sure, they look different rite; the first image has the title "Orders List" and the second image has "Orders by Customer", and so on...
 
If we pay close attention then technically the difference is really the output format, the underlying data is the same (orders information). By this time, I am sure most of you probably got the gist, what is my technique is and how it will help you generate multiple outputs using dynamic control of report generation.
 
 
Image: 1.2
 
 
Image: 1.3
 

How can one report produce four different outputs?

 
Imagine you have asked to develop a Sales Order System; one of the reporting requirements involved is to produce four different reports to calculate freight paid for all shipped orders.
 
In a typical scenario, you will create four individual reports as per the specification. Well, nothing wrong with this approach, we have done this in past and continuing to do so. However, since we do a lot of code reusing, why not try to reuse a report as a template and generate different outputs.
 
The quest to reuse the report led me to Ms Reporting Service. I am having a fun time doing this report reuse business. I thought let me share this with my friends here with the hope that it helps you the way it helped me.
 
The key to making your report generate more than one output is some of the design considerations. Here is what I did to generate four different outputs from this one report.
 

Report designs considerations

 
 
Image: 1.4
 
Careful report design consolidation is required to create a single reporting template, resulting in different outputs. We will start by making use of Table Control; first, we have to identify and lay down all the details columns that are common to all outputs. Please check the report in the attached code for details of formatting etc.
 

Dynamic data grouping

 
If you notice, apart from the detail section, the fact that makes all outputs look different is the way information grouped together. Now, you would start to wonder how I could change data grouping during run time to see different outputs.
 
Well, the solution to this problem is introducing some intelligence into our report, which the rendering engine can leverage on and produce the desired output. I am making use of the following two parameters to pass onto the report so it can act differently.
 
 
Image: 1.5
 
I will make use of the parReportType parameter to pass the following four values: O-Orders, C-Customer, S-City, and T-Country. This one letter type (O, C, S, T) provided as dynamic value to group the data before producing the output.
 
 
Image: 1.6
 
Our dose of intelligence to report designer is nothing but following Grouping Expression, which changes data group based on information supplied through parReportType:
  1. =iif(Parameters!parReportType.Value = "O","",  
  2. iif(Parameters!parReportType.Value = "C", Fields!CustomerID.Value,  
  3. iif(Parameters!parReportType.Value = "S",  
  4. Fields!ShipCity.Value,Fields!ShipCountry.Value))) 
If you are not sure what iif() is, then not to worry, MS Reporting uses VB.NET syntax for coding expressions and custom code. If you have done any custom coding for example with Crystal Reports, then interacting with MS Reporting Services will not be a big deal.
 
The expression supplies instruction to the rendering engine on how to group and sort the data based on our choice of report selection. It starts with checking if the choice is "O" which means simple output, not grouping. Subsequently, check for the rest of the choices and switch the behavior of report generation. We need to repeat the same expression in the sorting tab of the grouping and sorting properties window.
 
Handling of group header & footer
 
We are dealing with three different groups in this report and one output has no grouping required. We have to do the following to generate proper group names and handle the visibility property of the header & footer.
 
Apply the following expression to the group header & footer visibility property:
  1. =IIF(Parameters!parReportType.Value = "O", True, False) 
The above-mentioned expression will take care of hiding the group header & footer in case of default report "Order List" selected.
 
As the group changes dynamically, we do have to change the output to reflect the current scenario. If the user selects "Order by Customer" then we have to make sure to change the group header to "Customer: xyz" and so forth.
 
Following expression entered as group header title takes care of dynamically changing the header based on provided grouping criteria:
  1. =iif(Parameters!parReportType.Value = "O","",  
  2. iif(Parameters!parReportType.Value = "C",  
  3. "Customer: " & FIRST(Fields!CustomerID.Value),  
  4.  iif(Parameters!parReportType.Value = "S",  
  5. "City: " & FIRST(Fields!ShipCity.Value),  
  6. "Country: " & FIRST(Fields!ShipCountry.Value)))) 
Coding time
 
So far so good, we have put all sorts of intelligence into our report template; we made sure all steps are taken to achieve the desired result. However, what prompts the report to act in a certain way? How does the report know, should it generate a report based on Customer or City, or it should ignore grouping altogether and produce a plaint orders list?
 
Now, we have done the design part of the report. Now we have to provide a mechanism to collect data from SQL Server and bind it to the reporting engine. Out of many different ways data can be bound to a reporting engine, my favorite is using DataSet.
 
 
Image: 1.7
 
Make sure to have DataSet ready as per image 1.7.
 
I have written a method called loadReport and passing a single parameter to it as reportType. I am calling this method from all four buttons, every time passing a different argument.
 
Following is the code for the method:
  1. private void loadReport(String reportType) {  
  2.     //declare connection string  
  3.     string cnString = @ "Data Source=(local); Initial Catalog=northwind;" + "User Id=northwind;Password=northwind";  
  4.   
  5.     //use following if you use standard security  
  6.     //string cnString = @"Data Source=(local);Initial  
  7.     Catalog = northwind;  
  8.     Integrated Security = SSPI ";  
  9.   
  10.     //declare Connection, command, and other related objects  
  11.     SqlConnection conReport = new SqlConnection(cnString);  
  12.     SqlCommand cmdReport = new SqlCommand();  
  13.     SqlDataReader drReport;  
  14.     DataSet dsReport = new dsOrders();  
  15.   
  16.     try {  
  17.         //open connection  
  18.         conReport.Open();  
  19.   
  20.         //prepare connection object to get the data through reader and  
  21.         populate into dataset  
  22.         cmdReport.CommandType = CommandType.Text;  
  23.         cmdReport.Connection = conReport;  
  24.         cmdReport.CommandText = "Select * FROM Orders Order By OrderID ";  
  25.   
  26.         //read data from command object  
  27.         drReport = cmdReport.ExecuteReader();  
  28.   
  29.         //new cool thing with ADO.NET... load data directly from reader  
  30.         to dataset  
  31.         dsReport.Tables[0].Load(drReport);  
  32.   
  33.         //close reader and connection  
  34.         drReport.Close();  
  35.         conReport.Close();  
  36.   
  37.         //provide local report information to viewer  
  38.         reportViewer.LocalReport.ReportEmbeddedResource = "DataGrouping.rptOrders.rdlc";  
  39.   
  40.         //prepare report data source  
  41.         ReportDataSource rds = new ReportDataSource();  
  42.         rds.Name = "dsOrders_dtOrders";  
  43.         rds.Value = dsReport.Tables[0];  
  44.         reportViewer.LocalReport.DataSources.Add(rds);  
  45.   
  46.         //add report parameters  
  47.         ReportParameter[] Param = new ReportParameter[2];  
  48.   
  49.         //set dynamic properties based on report selection  
  50.         //O-order, C-Customer, S-City, T-Country  
  51.         switch (reportType) {  
  52.             case "O":  
  53.                 Param[0] = new ReportParameter("parReportTitle",  
  54.                     "Orders List");  
  55.                 Param[1] = new ReportParameter("parReportType""O");  
  56.                 break;  
  57.             case "C":  
  58.                 Param[0] = new ReportParameter("parReportTitle",  
  59.                     "Orders by Customer");  
  60.                 Param[1] = new ReportParameter("parReportType""C");  
  61.                 break;  
  62.             case "S":  
  63.                 Param[0] = new ReportParameter("parReportTitle",  
  64.                     "Orders by City");  
  65.                 Param[1] = new ReportParameter("parReportType""S");  
  66.                 break;  
  67.             case "T":  
  68.                 Param[0] = new ReportParameter("parReportTitle",  
  69.                     "Orders by Country");  
  70.                 Param[1] = new ReportParameter("parReportType""T");  
  71.                 break;  
  72.         }  
  73.   
  74.         reportViewer.LocalReport.SetParameters(Param);  
  75.   
  76.         //load report viewer  
  77.         reportViewer.RefreshReport();  
  78.     } catch (Exception ex) {  
  79.         //display generic error message back to user  
  80.         MessageBox.Show(ex.Message);  
  81.     } finally {  
  82.         //check if connection is still open then attempt to close it  
  83.         if (conReport.State == ConnectionState.Open) {  
  84.             conReport.Close();  
  85.         }  
  86.     }  

Code-behind each button is as follows:
  1. private void btnOrders_Click(object sender, EventArgs e) {  
  2.     //orders list  
  3.     loadReport("O");  
  4. }  
  5.   
  6. private void btnByCustomer_Click(object sender, EventArgs e) {  
  7.     //orders by customer  
  8.     loadReport("C");  
  9. }  
  10.   
  11. private void btnByCity_Click(object sender, EventArgs e) {  
  12.     //orders by city  
  13.     loadReport("S");  
  14. }  
  15.   
  16. private void btnByCountry_Click(object sender, EventArgs e) {  
  17.     //orders by country  
  18.     loadReport("T");  

Conclusion

 
I would love to participate in any discussion about the pros and cons of this approach. To me, a template-based approach and reusability make more sense than anything else. Any constructive criticism is always welcome.
 
I would leave you with this final thought here, if you think that I was wrong in saying, "Four birds with one stone", instead I could have said, "Seven birds with one stone" then you are 100% correct my friend. I would leave it that up to you to figure it out. This is a bonus exercise for you if you end up playing with the attached code.
 
Ok, here is the hint: Imagine an end-user asks you I need another three reports, but this time I do not care about details. Just give me Customer...Freight Total, same for City and Country. Therefore, the solution is, HIDE THE DETAIL!


Similar Articles