您可以使用
ReportForm下面的单个符号,并将数据和报告名称传递给它。报告表单应包含一个
ReportViewer控件和以下代码:
public partial class ReportForm : Form{ public ReportForm() { InitializeComponent(); this.Load+=new EventHandler(ReportForm_Load); } public Object ReportData { get; set; } public string ReportName { get; set; } private void ReportForm_Load(object sender, EventArgs e) { var rds = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", this.ReportData); this.reportViewer1.LocalReport.DataSources.Clear(); this.reportViewer1.LocalReport.DataSources.Add(rds); var path = System.IO.Path.Combine(Application.StartupPath, "Reports", this.ReportName); reportViewer1.LocalReport.ReportPath = path; this.reportViewer1.RefreshReport(); }}用法
您可以使用
ReportForm这种方式:
var f = new ReportForm();DataTable table = new DataTable(); var command = Properties.Settings.Default.Command; var connection = Properties.Settings.Default.Connection; using (var adapter = new SqlDataAdapter(command, connection)) adapter.Fill(table)f.ReportName = "Report1.rdlc" f.ReportData = table;f.ShowDialog();
笔记
ReportViewer控件显示RDLC报告。RDL报表应托管在SQL Server报表服务上。看来您想在客户端计算机上而不是在SSRS上获得报告。如果是这种情况,则需要RDLC报告。尽管RDL和RDLC具有相同的XML模式,但是从技术上讲,您似乎需要RDLC。
您说过, RDL文件通常是设计一次的, 因此客户可以在其计算机上拥有报告文件,并且您可以仅按报告的地址将报告加载到报告视图中,甚至可以将这些报告放入解决方案中并将其嵌入为资源。将报表设置为嵌入式资源时,可以按其名称加载报表:
reportViewer1.LocalReport.ReportEmbeddedResource = "Sample.Reports.Report1.rdlc";
或按路径加载报告:
var path = System.IO.Path.Combine(Application.StartupPath, "Reports", "Report1.rdlc");reportViewer1.LocalReport.ReportPath = path;
您说过 ,SQL通常是一个常量。 并且 我们的用户不与我们共享连接, 因此您可以使用
Settings.settings
并添加2个属性(Command
应用程序范围Connection
和用户范围)。因此,您可以让用户在运行时更改连接字符串,然后以这种方式加载数据并将数据传递给您ReportForm
:DataTable table = new DataTable();
var command = Properties.Settings.Default.Command;
var connection = Properties.Settings.Default.Connection;
using (var adapter = new SqlDataAdapter(command, connection))
adapter.Fill(table)
//Pass table to ReportForm实际上,sql命令可以是动态的,但它应保持恒定的结果模式。结果列名称不应更改,因为报表引擎使用查询列名称在报表字段中显示数据。因此,您也可以将
Command
属性创建为User
设置。关于 But但是,在任何流行的RDBMS中都是一种解决方案, 最好使用依赖项注入来注入可以为您加载数据的库。这样,您可以为不同的DBMS使用不同的dll,并在需要时注入合适的dll。



