1.建立两张报表:RepMain.rdlc / RepMainChild.rdlic
2.在RepMain.rdlc中添加Subreport控件
3.核心代码如下
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
namespace 子报表
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.LoadReport();
}
private void button1_Click(object sender, EventArgs e)
{
this.LoadReport();
}
protected void LoadReport()
{
string depid = this.txtDepid.Text.Trim().ToString();
string sql = @"select depid,depname,parents from dep where 1=1";
if (depid.Length>0)
{
sql += " and depid='" + depid + "'";
}
DataTable dt = DBUtil.getDataTable(sql);
ReportDataSource rds = new ReportDataSource("DataSet1", dt);
//为报表的子报表添加注册事件
this.reportViewer1.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();
}
void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
{
string depid = this.txtDepid.Text.Trim().ToString();
string sql = @"select userid,username,depid from users where 1=1";
if (depid.Length > 0)
{
sql += " and depid='" + depid + "'";
}
DataTable dt = DBUtil.getDataTable(sql);
ReportDataSource rds = new ReportDataSource("DataSet1", dt);
//e即代表触发的report.LocalReport类型
e.DataSources.Clear();
e.DataSources.Add(rds);
}
}
}