将datagridview中的数据显示到reportviewer C#

我有一个datagridview,我想将数据传递给reportviewer,所以这样我就可以轻松地打印和导出到pdf / excel。 我该怎么做? 还是有另一种解决scheme来实现我的目标? 谢谢! 🙂

既然你想把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 

多数民众赞成,你完成了!