Monday, 1 July 2013

Report View Example2

ASP.net - RDLC Report in ASP.net


n this article i will show you how to generate RDLC report in ASP.net web application.

Step 1
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a northwind database into MS-SQL server

Step 3
Create a web application and give solution name as SolRDLCReportASP.

Step 4
Add AJAX ScriptManger on page,it is look like this

  1. <asp:ScriptManager ID="ScriptManager1" runat="server">  
  2. </asp:ScriptManager>  

Step 5
Add a ReportViwer control on page from toolbox,it is look like this




Click on image for better view
  1. <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
  2.             <ContentTemplate>  
  3.                   
  4.                 <rsweb:ReportViewer ID="EmployeeReport" runat="server" Width="100%" Height="100%">  
  5.               
  6.                 </rsweb:ReportViewer>  
  7.   
  8.             </ContentTemplate>  
  9.         </asp:UpdatePanel>  

Finally Presentation part done now we Create DataSet Schema and Report Design.


Step 6

First We create a DataSet Schema.it can be define Dataset schema without connecting to any datasource.
Add a DataSet Schema,right click on Add new Item,select DataSet from installed Visual Studio templates and name it NorthwindDataSet and click on add button,it is look like this


Click on image for better view

Step 7
Click on toolbox icon,it is look like this


Click on image for better view

Select DataTable from Toolbox and drag and drop to the dataset design editor,it is look like this


Click on image for better view

Finally Add column to schema,it is look like this


Click on image for better view

DataSet Schema is ready now we create Report Design in web application.

Step 8
Add a RDLC Report,First Create App_Data folder,right click on App_Data folder,select  Add new Item,select Report from installed Visual Studio templates and name it NorthwindReport and click on add button,it is look like this


Click on image for better view

Step 9
Add DataSet Schema to the report,it is look like this


Click on image for better view

In the next dialog, give the dataset a name called EmployeeDataSet. Change the data source to NorthwindDataSet and select available dataset Employee and click OK,it is look like this


Click on image for better view

Step 10
Add Header and Footer on report,it is look like this


Click on image for better view

In Header Section Add TextBox from toolbox,it is look like this


Click on image for better view

In Footer Section Add Page number from build in field,it is look like this


Click on image for better view

Step 11
Add Table from toolbox for display employee data,it is look like this


Click on image for better view

Drag and Drop all Employee Fields from NorthwindDataSet into table,it is look like this


Click on image for better view

Finally Report is ready now we move to programming part.

Step 12
Bind Employee data to Dataset Schema,it is look like this
  1. #region Bind Employee Data to DataSet Schema  
  2.    /// <summary>  
  3.    /// Get Employee data from Northwind database and bind in NorthwindDataSet  
  4.    /// </summary>  
  5.    /// <returns>DataTable</returns>  
  6.    private DataTable GetEmployeeData()  
  7.    {  
  8.        try  
  9.        {  
  10.            // Open Sql Connection  
  11.            SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");  
  12.            SqlCon.Open();  
  13.   
  14.            // Create a Command  
  15.            SqlCommand SqlComm = new SqlCommand();  
  16.            SqlComm.Connection = SqlCon;  
  17.            SqlComm.CommandType = CommandType.Text;  
  18.            SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";  
  19.   
  20.            // Create instance of Northwind DataSetXSD  
  21.            NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();  
  22.   
  23.            // Set a Data Commands  
  24.            SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);  
  25.            SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.  
  26.   
  27.            return EmployeeDt;  
  28.   
  29.        }  
  30.        catch (Exception ex)  
  31.        {  
  32.            throw new Exception(ex.Message);  
  33.        }  
  34.    }  
  35.  
  36.    #endregion  

Step 13
Display Report in Report Viewer,it is look like this
  1. #region Display Report  
  2.     /// <summary>  
  3.     /// Display Report in Report Viewer  
  4.     /// </summary>  
  5.     private void DisplayReport()  
  6.     {  
  7.         try  
  8.         {  
  9.            // Clear the Data Source   
  10.            EmployeeReport.LocalReport.DataSources.Clear();  
  11.   
  12.            // Set a DataSource to the report  
  13.   
  14.            // First Parameter - Report DataSet Name  
  15.            // Second Parameter - DataSource Object i.e DataTable  
  16.            EmployeeReport.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet",GetEmployeeData()));  
  17.   
  18.            // OR Set Report Path  
  19.            EmployeeReport.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/App_Data/NorthwindReport.rdlc");  
  20.   
  21.            // Refresh and Display Report  
  22.            EmployeeReport.LocalReport.Refresh();  
  23.         }  
  24.         catch (Exception ex)  
  25.         {  
  26.             throw new Exception(ex.Message);  
  27.         }  
  28.     }  
  29.  
  30.     #endregion  

Call DisplayReport function on Page_Load event,it is look like this
  1. protected void Page_Load(object sender, EventArgs e)  
  2.    {  
  3.        try  
  4.        {  
  5.            if (IsPostBack == false)  
  6.            {  
  7.                DisplayReport();  
  8.            }  
  9.        }  
  10.        catch (Exception ex)  
  11.        {  
  12.            throw new Exception(ex.Message);    
  13.        }  
  14.    }  

Run the project.


Output




Click on image for better view


Full Code


1. .Aspx Page Code
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"  
  4.     Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>  
  5.   
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  7.   
  8. <html xmlns="http://www.w3.org/1999/xhtml">  
  9. <head runat="server">  
  10.     <title></title>  
  11. </head>  
  12. <body>  
  13.     <form id="form1" runat="server">  
  14.     <div>  
  15.           
  16.         <asp:ScriptManager ID="ScriptManager1" runat="server">  
  17.         </asp:ScriptManager>  
  18.           
  19.         <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
  20.             <ContentTemplate>  
  21.                   
  22.                 <rsweb:ReportViewer ID="EmployeeReport" runat="server" Width="100%" Height="100%">  
  23.               
  24.                 </rsweb:ReportViewer>  
  25.   
  26.             </ContentTemplate>  
  27.         </asp:UpdatePanel>  
  28.           
  29.   
  30.           
  31.     </div>  
  32.     </form>  
  33. </body>  
  34. </html>  

2. Code behind
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using Microsoft.Reporting.WebForms;  
  10.   
  11. public partial class _Default : System.Web.UI.Page   
  12. {  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         try  
  16.         {  
  17.             if (IsPostBack == false)  
  18.             {  
  19.                 DisplayReport();  
  20.             }  
  21.         }  
  22.         catch (Exception ex)  
  23.         {  
  24.             throw new Exception(ex.Message);    
  25.         }  
  26.     }  
  27.  
  28.     #region Bind Employee Data to DataSet Schema  
  29.     /// <summary>  
  30.     /// Get Employee data from Northwind database and bind in NorthwindDataSet  
  31.     /// </summary>  
  32.     /// <returns>DataTable</returns>  
  33.     private DataTable GetEmployeeData()  
  34.     {  
  35.         try  
  36.         {  
  37.             // Open Sql Connection  
  38.             SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");  
  39.             SqlCon.Open();  
  40.   
  41.             // Create a Command  
  42.             SqlCommand SqlComm = new SqlCommand();  
  43.             SqlComm.Connection = SqlCon;  
  44.             SqlComm.CommandType = CommandType.Text;  
  45.             SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";  
  46.   
  47.             // Create instance of Northwind DataSetXSD  
  48.             NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();  
  49.   
  50.             // Set a Data Commands  
  51.             SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);  
  52.             SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.  
  53.   
  54.             return EmployeeDt;  
  55.   
  56.         }  
  57.         catch (Exception ex)  
  58.         {  
  59.             throw new Exception(ex.Message);  
  60.         }  
  61.     }  
  62.  
  63.     #endregion  
  64.  
  65.     #region Display Report  
  66.     /// <summary>  
  67.     /// Display Report in Report Viewer  
  68.     /// </summary>  
  69.     private void DisplayReport()  
  70.     {  
  71.         try  
  72.         {  
  73.            // Clear the Data Source   
  74.            EmployeeReport.LocalReport.DataSources.Clear();  
  75.   
  76.            // Set a DataSource to the report  
  77.   
  78.            // First Parameter - Report DataSet Name  
  79.            // Second Parameter - DataSource Object i.e DataTable  
  80.            EmployeeReport.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet",GetEmployeeData()));  
  81.   
  82.            // OR Set Report Path  
  83.            EmployeeReport.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/App_Data/NorthwindReport.rdlc");  
  84.   
  85.            // Refresh and Display Report  
  86.            EmployeeReport.LocalReport.Refresh();  
  87.         }  
  88.         catch (Exception ex)  
  89.         {  
  90.             throw new Exception(ex.Message);  
  91.         }  
  92.     }  
  93.  
  94.     #endregion  
  95. }  

Download
Download Source Code

Report using REPORT VIEWER example1

Designing and Developing Reports in ASP.NET consists of following steps:



  1. Creating a strongly-typed data set.
  2. Designing the report on the basis of dataset.
  3. Displaying the report using Reportviewer.
  4. Attaching dataset (data) to the reportviewer (report) dynamically at run time.

Let us follow each step in detail now:

STEP 1:

To design a report (locally) and embed it within our application, we first need to start with a strongly-typed data set. This data set will act as a data source for the report we are going to develop. At run-time, the data set gets automatically populated from the database, which finally is rendered using the "ReportViewer" control. 
  1. Open your Visual Studio 2005/2008 IDE and create a new web project or open an existing project.
  2. Right click on the solution and go for "Add New Item."
  3. Select "dataset" as the template and click on 'Add' to create the data set. 
    Add dataset
  4. It prompts you to place the dataset-related code in the "app_code" folder. Click on "OK." I gave the name of the dataset as AllRecordsWithCondition. Also, the datatable name should be given as dtAllRecordsWithCondition while creating table adapter in steps to follow.
  5. Once it creates the dataset, you should start the "TableAdapter Configuration Wizard" by right clicking. You can select any existing connection or create a new connection by hitting the "New Connection" button.
    Add table adapter
  6. Once you have selected the connection, click on "Next." At this level, it prompts for the connection string; simply press "Next". The next section asks for the command type, to which you select "Use SQL statements" and click "Next."
  7. Next, you can type your own SELECT statement to retrieve the data related to the report. You can also use the "Query Builder" button if you need to design a query in a GUI environment.
  8. Click "Next," make sure that you select both check boxes, then hit "Next" again.
  9. At this point, it gives you the results of your data set creation; check them and finally click "Finish."  
    Table adapter finish


STEP 2:

Now it is time to add a new embeddable report to our application:
  1. Using the Solution Explorer, right click on the project and go for "Add New Item." Select "Report" as the template, provide a name for your report and click "Add." 
  2. The name of the report file will end with the extension "rdlc," which stands for "report definition language for client" (or for local mode). If you deal with SQL Server 2005 Reporting Services, it will have the extension "rdl" only, i.e. server mode.
  3. You now land up in report designer, where you design/develop the reports. From the Toolbox, drag a table and drop it onto the layout.  You can observe that it shows an Excel-like spread sheet with only three rows.  The first row is for the header, the second is for detail (or records) and the third is for the footer.
  4. At this point, you need to drag the columns (of the data set) from "Website Data Sources" onto each cell in the second row of the Excel-type grid.  If "Website Data Sources" is not visible, you can make it visible by going to Data -> Show Data Sources. 
    Show data source
  5. Once you drag all the columns, your screen should look something like the following:
    Report design


STEP 3:

  1. Drag and drop the "ReportViewer" control from the toolbox on your web page.
  2. From the smart tag of the "ReportViewer" control, select "AllRecordWithCondition.rdlc" from the drop down.
    Add reportviewer
  3. Now, you can press F5 to execute the solution. You will be prompted for the "Web.config" modification for debugging, to which you respond by clicking on "OK."
  4. You should be able to see the report output now.

Report Output 

STEP 4:

Attaching dataset (data) to the reportviewer (report) dynamically at run time:

When you want to attach data sources dynamically at run time, you may need to add a few lines of code to your web page.
Following is the code used to achieve this:

            ReportViewer1.Visible = true;
            ReportDataSource rds = new ReportDataSource();
            ReportViewer1.Reset();
            ReportViewer1.ProcessingMode = ProcessingMode.Local;
            LocalReport rep = ReportViewer1.LocalReport;                      
            rep.Refresh();
            rep.ReportPath = "AllRecordsWithCondition.rdlc";
            //This name must be in "<datasetname>_<datatablename>" format. This name can also be seen in dataset's datasource view.
            rds.Name = "AllRecordsWithCondition_dtAllRecordsWithCondition";
            // Text in bold should be your datatable's name from your current dataset i.e. AllRecordsWithCondition.
            rds.Value = dtAllRecordsWithCondition.Tables[0]; 
            rep.DataSources.Add(rds);


NOTE: 

  1. The most important issue to remember from the above code is that the name of the report data source must match with the syntax of "<datasetname>_<datatablename>".
  2. At the time of writing this article, It was important to have the dataset created and attched to report at design time even when you want to create dataset and attach it to reportviewer at run time using step 4 above. The report won't work if you do not create the dataset at design time. The dependency may change in future releases of reportviewer.