【问题标题】:Show data from datagridview to reportviewer C#从datagridview显示数据到reportviewer C#
【发布时间】:2015-09-27 14:59:31
【问题描述】:

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

【问题讨论】:

  • 您的DataGridView 使用哪种类型的DataSource

标签: c# excel pdf datagridview reportviewer


【解决方案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

就是这样,你完成了!

【讨论】:

  • 感谢您的回答。一般来说,我是一个关于 C# 和 Visual Studio 的新手。我对您的代码有一些疑问:1)我需要在同一个表单中使用 datagridview 和 reportviewer? 2)在哪个事件中我需要放置它们?在一个按钮?表单加载?我知道这些问题很愚蠢,但我现在正在学习 :) 谢谢!
  • 不需要datagridview和reportviewer在同一个表单中。您可以将一个表单上的 Gridview 之间的数据传递到另一个表单上的 ReportViewer,您可以在谷歌上搜索“在 C# 中的 Windows 表单之间传递数据”以获得一个想法。但由于您是新手,我建议您以相同的形式使用 datagridview 和 reportviewer。一旦您了解了如何将数据从 GridView 传递到 reportviewer,您可能会尝试使用不在同一个表单上的两个控件来实现相同的效果。希望这会有所帮助。
  • Ans-2:尝试在您的 Gridview 旁边添加一个按钮(按钮文本:“生成报告”),然后在此按钮的单击事件上放置用于绑定报告查看器的代码。
  • 感谢您的回答。我得到了错误:我把datagridview和reportviewer放在同一个表单中;我将第一个代码放入 form_load;我将第二个代码放入按钮中。当我运行我的项目时,我收到了这个错误:“无法将'System.Data.DataSet'类型的对象转换为'System.Windows.Forms.BindingSource'”我该怎么办? :)
  • 在第一个代码中进行以下更正: var bs = (BindingSource)GridView1.DataSource; var dt = (DataTable) bs.DataSource;这将消除错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2011-09-15
  • 1970-01-01
相关资源
最近更新 更多