一个通用的报表显示窗口(WindowsForms)
这也是这两天课堂上的一个范例。我们考虑到有很多报表,不可能为所有的报表单独定义一个窗口来显示,所以最后重构成一个通用的窗口
后台代码
using System; using Microsoft.Reporting.WinForms; namespace NorthwindApplication { public partial class ReportForm : NorthwindApplication.FormTemplate { public ReportForm() { InitializeComponent(); } public ReportForm( string formTitle, string reportTitle, string reportPath, params ReportDataSource[] datasource) : this() { this.Text = formTitle; this.FormTitle.Text = reportTitle; this.reportViewer1.LocalReport.ReportPath = reportPath; this.reportViewer1.LocalReport.DataSources.Clear(); foreach (var item in datasource) { this.reportViewer1.LocalReport.DataSources.Add(item); } } private void ReportForm_Load(object sender, EventArgs e) { this.reportViewer1.RefreshReport(); } } }
主窗体调用代码
//这里读取数据,然后实例化报表,然后显示报表 var formTitle = "员工订单报表"; var context = new NorthwindDataContext(); var employee = context.Employees.Where( emp => emp.EmployeeID == 1); if (employee != null) { var temp = employee.FirstOrDefault(); var reportTitle = temp.FirstName + "," + temp.LastName; var reportPath = "EmployeeOrderReport.rdlc"; ReportForm report = new ReportForm( formTitle, reportTitle, reportPath, new ReportDataSource( "NorthwindApplication_Employees", employee), new ReportDataSource( "NorthwindApplication_Orders", temp.Orders.ToArray())); report.MdiParent = this; report.WindowState = FormWindowState.Maximized; report.Show(); }
窗体显示的大致效果如下