Using the ReportViewer control in ASP.NET 2.0
Author:Eve Cole
Update Time:2009-07-01 16:43:40
Translation of this article: webabcd
introduce
A common requirement for any data-driven application is reporting. However, this very important feature is not provided to us in ASP.NET 1.x. Fortunately, however, the ReportViewer control that comes with .NET 2.0 can meet some of your basic needs for reports. I'll show you how to use this control in this article. The ReportViewer control can be used in both web programs and windows programs. Here, I will only introduce how to use it in web programs.
Report example
We assume that we want to generate a customer information list as shown below:
The report above is a very simple list of customer information grouped by country. The data for the report is obtained from the Customers table of the Northwind database. By default, it displays all customer information. However, you can also have it display information about customers belonging to a country you specify.
The report is designed using the ReportViewer control, which can obtain data from a strongly typed DataSet or a custom object collection. In actual program development, we often use a three-tier architecture, and the data obtained is often a DataSet or a generic collection obtained from the business layer. Here, I plan to use a generic collection as the data source instead of a strongly typed DataSet.
Create class library
First, open Visual Studio and create a class library project called ReportViewerLib. Add a class named Customer as shown below:
using System; using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Collections.Generic; namespace ReportViewerLib { public classCustomer { public string strCustomerID; public string strCompanyName; public string strContactName; public string strCountry;
public string CustomerID { get { return strCustomerID; } set { strCustomerID = value; } }
public string CompanyName { get { return strCompanyName; } set { strCompanyName= value; } }
public string ContactName { get { return strContactName; } set { strContactName= value; } }
public string Country { get { return strCountry; } set { strCountry= value; } }
public static List |
GetCustomersForCountry(string country) { SqlConnection cnn=new SqlConnection( ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString); SqlCommand cmd=new SqlCommand(); cmd.Connection=cnn; cmd.CommandText="select CustomerID,CompanyName,ContactName,Country from customers where country=@country"; SqlParameter p=new SqlParameter ("@country",country); cmd.Parameters.Add(p); cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); List |
(); while (reader.Read()) { Customer c = new Customer(); c.CustomerID = reader.GetString(0); c.CompanyName = reader.GetString(1); c.ContactName = reader.GetString(2); c.Country = reader.GetString(3); list.Add(c); } cnn.Close(); return list; }
public static List |
GetAllCustomers() { SqlConnection cnn = new SqlConnection( ConfigurationManager.ConnectionStrings ["NorthwindConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = cnn; cmd.CommandText = "select CustomerID,CompanyName,ContactName,Country from customers"; cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); List |
(); while (reader.Read()) { Customer c = new Customer(); c.CustomerID = reader.GetString(0); c.CompanyName = reader.GetString(1); c.ContactName = reader.GetString(2); c.Country = reader.GetString(3); list.Add(c); } cnn.Close(); return list; }
} }
|
The Customer class defines four public properties, namely CustomerID, CompanyName, ContactName and Country. After that, there are two static methods contained in this class – GetCustomersForContry() and GetAllCustomers(). These two methods are relatively simple. One returns all customer information belonging to a certain country, and the other returns all customer information. First open the connection to the Northwind database, and then execute the SELECT query through the SqlCommand object. After that, use the SqlDataReader object to get the data. Traverse this SqlDataReader object, create a Customer object each time inside it, then set its various properties, and finally add it to the generic collection of Customer objects. At the end of the class, the generic collection of Customer objects is returned to the caller.
Create data source
When designing a report, you need to specify a data source for it in your project. To add a data source to your project you can do this by selecting the Data menu -> Add New Data Source. Then the dialog box shown below will appear:
Your data source can be a database, a web service, or an object. In this case we selected Object. Then click the "Next" button, and an interface for us to select a data source will pop up. We chose the Customer class (as shown in the figure below).
Click the "Finish" button to complete the data source configuration wizard. In this way, you have added a new data source to your class library. If you want to view the data source, you can do this. Select the "Data" menu -> Show data source, and the interface as shown below will appear:
Design reports
Next add a report. Right-click on the project and select "Add New Item". Select "Report" in the dialog box and click the "Add" button (as shown in the figure below). In this way, we have added a file named "Report1.rdlc". The .rdlc file is a report file, which saves the report layout and data mapping.
Once you open the Report1.rdlc file, a set of report-related controls will be displayed in the Visual Studio toolbox (as shown below).
Among these controls, the "Text Box" control and the "Table" control are very commonly used. The "Text Box" control is used to display a piece of static text or an expression. The "Table" control is used to display tabular data, and the results generated by it will be displayed in the "body" of your report.
The designed report is shown below:
At the head of the "Header" section of the report, there is a text box whose Value property is "Customer Listing". There is another text box below this text box, and the value of its Value property is "=Parameters!SubTitle.Value". What it means is that the value of the text box comes from the parameter named SubTitle. How do we define parameters? This requires adding parameters in the ReportParameters property of the report. The opened report parameters dialog box is shown in the figure below:
Please note: Setting the parameters is done in our .NET code.
If you want to display the date on the report, just set the Value property of the relevant text box to "=FormatDateTime(ToDay(),DateFormat.ShortDate)". One of the great advantages of reports is that they have many built-in functions, such as ToDay() and FormatDateTime. In this example, we use the FormatDateTime() function to display the current date (ToDay()) in ShortDate format.
Now, drag a "Table" control from the toolbox onto your report. By default, the "Table" control has 3 rows and 3 columns. The 3 rows are: table header, detailed information and table footer. Of course, you can also add rows and columns to the Table control. Drag the CustomerID, CompanyName, ContactName, and Country properties from the data source window onto the details row of your Table control. In this way, the system will automatically add a text box and set its properties to =Fields!CustomerID.Value, =Fields!CompanyName.Value and so on. At this point, column headers will also be automatically added. Of course, you can also make the modifications you need according to your needs.
Next, we want to group the records by the country to which the customer belongs. Right-click on the border of the details row and select Insert Group (as shown in the image below).
Then the dialog box shown below will appear:
In the "Sort" tab, select "=Fields!Country.Value" as the expression and "Ascending" as the sort direction.
Those are the things, very simple. In this way, we have completed the design of the report.
Show report
Create a new web site named "ReportViewerDemo". Add a reference to the ReportViewerLib assembly so that the assembly will be copied to the BIN directory of your web site. After that, add the Report1.rdlc file to your web site. Drag a ReportViewer control in the "Data" tab of the toolbox to your Default.aspx page, open the smart tag panel of the ReportViewer control, and select Report1.rdlc in the "Select Report" drop-down box, as shown in the figure below :
After selecting the report file, the system will automatically add an object data source control with the TypeName property as Customer. You can verify this in the configuration wizard of the object data source control.
Next, drag a DropDownList control to the header of the page and set four options for it – All, USA, UK, and Brazil. Also set its AutoPostBack property to True. Then, open the configuration wizard of the data source control and set the "SELECT" operation to the SelectCustomersForCountry() method.
Set the country parameter of the SelectCustomersForCountry() method to the SelectedValue of DropDownList1.
By default, all customer information is displayed in the report. When you select a country in the DropDownList, the customer information belonging to the country you selected will be displayed in the report. To complete such a function, we only need to handle the SelectedIndexChanged event of DropDownList.
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e) { if (DropDownList1.SelectedValue == "All") { ObjectDataSource1.SelectMethod = "GetAllCustomers"; ObjectDataSource1.SelectParameters.Clear(); ReportParameter param = new ReportParameter ("SubTitle", "List of all the customers"); ReportParameter[] p ={ param }; ReportViewer1.LocalReport.SetParameters(p); } else { ObjectDataSource1.SelectMethod = "GetCustomersForCountry"; ObjectDataSource1.SelectParameters[0].DefaultValue = DropDownList1.SelectedValue;
ReportParameter param = new ReportParameter ("SubTitle", "List of customers for a country"); ReportParameter[] p ={ param }; ReportViewer1.LocalReport.SetParameters(p); } } |
This code first checks the SelectedValue property of the DropDownList control. If it is "All", set the SelectMethod property of the data source control to GetAllCustomers. In addition, we also need to clear the SelectParameters collection because the GetAllCustomers() method does not require any parameters. Next, we create an instance of the ReportParameter class and set the report's parameter name and value in its constructor. Recall the parameters we defined when designing the report. Then create a ReportParameter array. Call the SetParameters() method with this array as its parameter. The "else" code block is also very simple, that is, the method used becomes GetCustomersForCountry().
Those are the things, very simple. The report has been completed. You can run the Default.aspx page to see the effect. Note that the ReportViewer control has built-in export features, which allows you to export reports to Excel or PDF format. The ReportViewer control also has many properties, you can explore them yourself.
Summarize
The ReportViewer control of ASP.NET provides many basic functions of reports. In this article, we use the object data source control to develop a report. We created a class library and a data source. Finally, use the ReportViewer control to display the report.