设置本地报告的数据源 – .NET和报告查看器
我创建了一个自定义控件(带有报表查看器的Windows窗体)。 我有以下代码来加载本地报告:
包含在CustomReportViewer类中
//Load local report this.reportViewer1.ProcessingMode = ProcessingMode.Local; //enable loading of external images this.reportViewer1.LocalReport.EnableExternalImages = true; //pass the report to the viewer using (FileStream stream = new FileStream(filename, FileMode.Open)) { this.reportViewer1.LocalReport.LoadReportDefinition(stream); }
我用这个叫:
CustomReportViewer reportViewer = new CustomReportViewer();
这工作正常,出现一个包含报表查看器控件的窗体, 但我收到以下消息:
A data source instance has not been supplied for the data source "ReportData"
我不完全确定如何设置数据源? 我需要的数据存储在一个远程数据库中…我该怎么做来设置这个连接?
您需要创建一个ReportDataSource ,并设置其Value
属性 – 例如DataTable
和IEnumerable
是受支持的源
作为示例,假设存在一个返回DataSet的方法,使用单个DataTable
匹配报表所需的列:
DataSet ds = SomeMethodToRetrieveDataSet(); // eg via DataAdapter // If your report needs parameters, they need to be set ... ReportParameter[] parameters = new ReportParameter[...]; ReportDataSource reportDataSource = new ReportDataSource(); // Must match the DataSource in the RDLC reportDataSource.Name = "ReportData"; reportDataSource.Value = ds.Tables[0]; // Add any parameters to the collection reportViewer1.LocalReport.SetParameters(parameters); reportViewer1.LocalReport.DataSources.Add(reportDataSource); reportViewer1.DataBind();
请注意,将RDLC嵌入到程序集中通常更容易,而不必保留单独的RDLC文件。 通过选择RDLC上的Build Action
作为Embedded Resource
来执行此Build Action
,然后您可以设置ReportEmbeddedResource
属性:
reportViewer1.LocalReport.ReportEmbeddedResource = "MyOrganisation.MyAssembly.NameSpace.MyReportName.rdlc";
请注意,资源字符串必须包含资源的完全限定名称(包括Assembly)。
对我来说,关键在于StuartLC如上所述……进一步说明当他说“必须匹配RDLC中的DataSource”时……它实际上certificate是“DataSetName”元素值re:
我一遍又一遍地因为它被称为“DataSource”所以我一直使用DataSource元素名称但显然在rdl和rdlc文件中这确实表示DataSetName。 因此,请记住这一点是从上面借用我自己的Stuart借来的代码。 注意DataSetName元素值:
using (SqlConnection sqlConn = new SqlConnection(rvConnection)) using (SqlDataAdapter da = new SqlDataAdapter(rvSQL, rvConnection)) { DataSet ds = new DataSet(); da.Fill(ds); DataTable dt = ds.Tables[0]; this.reportViewer1.Reset(); this.reportViewer1.ProcessingMode = ProcessingMode.Local; this.reportViewer1.LocalReport.ReportPath = AppDomain.CurrentDomain.BaseDirectory + "ssrsExport.rdlc"; ReportDataSource reportDataSource = new ReportDataSource(); // Must match the DataSet in the RDLC reportDataSource.Name = "DataSet1"; reportDataSource.Value = ds.Tables[0]; this.reportViewer1.LocalReport.DataSources.Add(reportDataSource); this.reportViewer1.RefreshReport(); }