如何为EF数据源的许多报告重用一个ReportViewer控件?

时间:2012-09-25 13:52:47

标签: winforms reportviewer rdlc

我想坚持使用一个表单和ReportViewer控件,并在运行时分配各种报表和数据源。通过快速谷歌检查显示的各种复杂的解决方案促使我在这里问。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:6)

您需要一个包含ReportViewer控件,RDLC报告和数据源的表单;可能有多种方法可以实现这一点,但是您可以使用“报表管理器”类公开每个显示特定报表的方法(例如ShowOrdersReport()ShowTimeSheetReport()等) - 或者您可以定义一个带有ReportBase方法实现的基类Show()类,在需要时提示输入参数......无论什么工作,它基本上归结为:

var reportForm = new ReportViewerForm(); // instantiate the form
// load the report definition into the viewer:
reportForm.reportViewer1.LocalReport.ReportEmbeddedResource = "Namespace.Report.rdlc";

// loading the data works great with a DataSet:
var data = _reportingDataSet.Tables[0];
// create the ReportDataSource with the report data:
var reportDataSource = new ReportDataSource("rdsReportDataSource", data);

reportForm.ShowReport(new[] { reportDataSource });

在这里,您需要注入_reportingDataSet依赖项;如果您正在使用参数化存储过程,则需要在填充DataSet之前提示输出报告参数。

ShowReport()方法将数据源添加到LocalReport.DataSources,然后调用显示您指定的报告的RefreshReport()

public void ShowReport(IEnumerable<ReportDataSource> dataSources)
{
    foreach (var dataSource in dataSources) 
        reportViewer1.LocalReport.DataSources.Add(dataSource);

    reportViewer1.RefreshReport();
}

答案 1 :(得分:2)

如果您使用的是Crystal报表,请在点击加载报表按钮时使用此报表 CrystalReportViewer.ReportSource = ReportName

如果您使用的是MS ReportViewer控件,那么显示报告需要两个重要步骤

  1. 将报告文件路径分配给ReportViewer
  2. 设置数据源
  3. 例如,名为reportViewer1的ReportViewer控件需要显示SomeReport.rdlc文件,然后需要以下代码(比如单击按钮)

    this.reportViewer1.LocalReport.ReportPath = @"Add absolute path of rdlc file"//e.g. @"C:\SomeReport.rdlc" ;
    this.reportViewer1.RefreshReport();
    

    这只是一个简单的例子,为简单起见,如果需要显示数据库中的数据,只需在调用RefreshReport之前分配datasource属性,我就使用静态报告 e.g。

    this.reportViewer1.LocalReport.DataSources.Add(MyreportDataSource);
    

    其中MyreportDataSource是ReportDataSource类型的对象,您可以轻松地将任何ADO.net DataTable转换为ReportDataSource对象。

    我希望这么多信息能为您做到,如果您想查看更多细节,可以在这个位置推荐一篇非常好的文章

    http://www.c-sharpcorner.com/UploadFile/robo60/StandaloneRDLCReports11142007183516PM/StandaloneRDLCReports.aspx