显示数据从datagridview到reportviewer c#

本文关键字:reportviewer datagridview 数据 显示 | 更新日期: 2023-09-27 18:02:02

我有一个datagridview,我想把数据传递给reportviewer,这样我就可以轻松地打印和导出到pdf/excel。请问我该怎么做?或者是否有其他解决方案来实现我的目标?谢谢你!:)

显示数据从datagridview到reportviewer c#

既然要将GridView数据传递给ReportViewer,那么您要做的第一件事就是检索GridView的数据源,如下所示:

BindingSource bs = (BindingSource)GridView1.DataSource;//You should first convert DataSourse into Binding Sourse
DataTable dt = (DataTable) bs.DataSource; //Get GridView data source to Data table

现在你在DataTable dt中获得了GridView数据,你可以将ReportViewer绑定到DataTable,如下所示:

ReportViewer ReportViewer1 = new ReportViewer(); //Your ReportViewer Control
ReportDataSource rds = new ReportDataSource("DataSet1_Customers_DataTable1",dt); // ReportViewerDataSource : ReportViewer is to be bind to this DataSource
ReportViewer1.LocalReport.DataSources.Clear(); // Clear the Previous DataSource of ReportViewer
ReportViewer1.LocalReport.DataSources.Add(rds); //bind ReportViewer1 to the new datasource(Which you wish)
ReportViewer1.LocalReport.Refresh(); // Refresh the ReportViewer Control, ReportViewer1 in this case

就这些,你完成了!