如何将数据表加载为ReportDataSource?

我想做的事情如下:

this.reportViewer.LocalReport.DataSources.Clear(); DataTable dt = new DataTable(); dt = this.inputValuesTableAdapter.GetData(); Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(); rprtDTSource = dt; // this line generates exception //this.reportViewer.LocalReport.DataSources.Add(rprtDTSource); this.reportViewer.RefreshReport(); 

如何将数据表加载为ReportDataSource?

当前代码生成: “无法将类型’System.Data.DataTable’隐式转换为’Microsoft.Reporting.WinForms.ReportDataSource’”

您没有正确初始化ReportDataSouce。 尝试一下:

 this.reportViewer.LocalReport.DataSources.Clear(); DataTable dt = new DataTable(); dt = this.inputValuesTableAdapter.GetData(); Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt); this.reportViewer.LocalReport.DataSources.Add(rprtDTSource); this.reportViewer.RefreshReport(); 

此外,您可能需要将第一个参数更改为ReportDataSource构造函数,以设置报表所期望的数据源的名称。

我相信麦迪逊上面的回答是正确的,但是对于Datasource.Name属性,可能需要强调Luke关于使用.rdlc报告文件中命名的DataSet名称的评论。 对我而言,这是让我的应用无法工作的主要问题。 可以通过使用“打开方式…”命令将.rdlc文件作为XML文件打开来找到它。 我认为默认只是“DataSet1”:

     BusinessEntityID System.Int32  

我犯的另一个错误是不在调试(或发布)文件夹中包含.rdlc文件。 通过右键单击解决方案资源管理器中的.rdlc文件,然后单击属性,然后将“复制到输出目录”设置为“始终复制”,可以解决此问题。

一旦这两个部分得到纠正,我的程序就可以在控制台应用程序中使用ReportViewer生成一个没有界面的PDF文件。

 this.reportViewer1.LocalReport.DataSources.Clear(); reportViewer1.Reset(); reportViewer1.LocalReport.ReportEmbeddedResource = "Your Report Name.rdlc"; SqlConnection con = new SqlConnection(); con.ConnectionString = "Connection"; con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = "Select * from YourTableName"; DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader()); con.Close(); ReportDataSource rprtDTSource= new ReportDataSource(); rprtDTSource.Name = "reportDataSetName"; rprtDTSource.Value = dt; this.reportViewer1.LocalReport.DataSources.Add(rprtDTSource); this.reportViewer1.RefreshReport(); 

想象一下,您的RDLC文件的DataSources块如下所示:

然后相关代码应该是:

string name =“DataSet1_Lot”; // 这必须存在于RDLC文件中 DataTable dt = new DataTable();

Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(name,dt);