显示报表
新建一个名为“ReportViewerDemo”的web站点。 添加ReportViewerLib程序集的引用,这样该程序集就会拷贝到你的web站点的BIN目录下。 之后,把Report1.rdlc文件添加到你的web站点中。 在工具箱的“数据”选项卡中拖拽一个ReportViewer控件到你的Default.aspx页上, 打开ReportViewer控件的智能标记面板,在“选择报表”的下拉框中选择Report1.rdlc,如下图所示:
选择好报表文件后,系统会自动地添加一个TypeName属性为Customer的对象数据源控件。 你可以在对象数据源控件的配置向导中验证一下。

接下来,拖拽一个DropDownList控件到页的头部,并为其设置4个选项 – All、USA、UK和Brazil。 同时设置它的AutoPostBack属性为True。 然后,打开数据源控件的配置向导,设置“SELECT”操作为SelectCustomersForCountry()方法。
 
设置SelectCustomersForCountry()方法的country参数为DropDownList1的SelectedValue。
 
默认情况下,将在报表中显示所有顾客信息。 当你在DropDownList选择了一个国家的时候,报表中就会显示属于你所选择的国家的顾客信息。 要完成这样的功能,我们只需要处理DropDownList的SelectedIndexChanged事件。
InBlock.gif protected void DropDownList1_SelectedIndexChanged
InBlock.gif( object sender, EventArgs e)
InBlock.gif{
InBlock.gif
InBlock.gif if (DropDownList1.SelectedValue == "All")
InBlock.gif{
InBlock.gif        ObjectDataSource1.SelectMethod = "GetAllCustomers";
InBlock.gif        ObjectDataSource1.SelectParameters.Clear();
InBlock.gif        ReportParameter param = new ReportParameter
InBlock.gif        ( "SubTitle", "List of all the customers");
InBlock.gif        ReportParameter[] p ={ param };
InBlock.gif        ReportViewer1.LocalReport.SetParameters(p);
InBlock.gif
InBlock.gif}
InBlock.gif else
InBlock.gif{
InBlock.gif        ObjectDataSource1.SelectMethod = "GetCustomersForCountry";
InBlock.gif        ObjectDataSource1.SelectParameters[0].DefaultValue    
InBlock.gif        = DropDownList1.SelectedValue;
InBlock.gif
InBlock.gif        ReportParameter param = new ReportParameter
InBlock.gif        ( "SubTitle", "List of customers for a country");
InBlock.gif        ReportParameter[] p ={ param };
InBlock.gif        ReportViewer1.LocalReport.SetParameters(p);
InBlock.gif
InBlock.gif}
InBlock.gif
InBlock.gif}
 
这段代码首先检查DropDownList控件的SelectedValue属性。 如果是“All”的话就设置数据源控件的SelectMethod属性为GetAllCustomers。 另外,我们还需要清空SelectParameters集合,因为GetAllCustomers()方法不需要任何参数。 接下来,我们创建一个ReportParameter类的实例,并在其构造函数中设置报表的参数名和参数值。 回忆一下我们在设计报表时定义的参数。 然后再创建一个ReportParameter数组。 调用SetParameters()方法,并用这个数组作为其参数。 “else”代码块也是非常地简单,就是使用的方法变成了GetCustomersForCountry()而已。

就是这些东西,很简单吧。 报表已经搞定了。 你可以运行一下Default.aspx页看看效果。 注意,ReportViewer控件已经内置了导出特性,它允许你把报表导出为Excel或PDF格式。 ReportViewer控件还很多的属性,你可以自己摸索一下。


总结
ASP.NET的ReportViewer控件提供了很多报表的基本功能。 在本文中,我们使用了对象数据源控件来开发一个报表。 我们创建了一个类库和一个数据源。 最后使用ReportViewer控件来显示报表。


作者:Bipin Joshi
Email:http://www.dotnetbips.com/contact.aspx
简介:Bipin Joshi是DotNetBips.com的管理员。他是http://www.binaryintellect.com/的发起人,这个公司提供.NET framwork的培训和咨询服务。他在印度孟买为开发者提供培训。他也是微软的MVP(ASP.Net)和ASPInsiders的会员。