将数据从datagridview显示到reportviewer C#

时间:2015-07-09 09:51:27

标签: c# excel pdf datagridview reportviewer

我有一个datagridview,我想将数据传递给reportviewer,因此我可以轻松地打印并导出到pdf / excel。 我该怎么办?还是有其他解决方案来实现我的目标?谢谢! :)

1 个答案:

答案 0 :(得分:1)

由于你想将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

这就是全部,你已经完成了!