星期五, 3月 05, 2021

[RV] 子報表

把該篇筆記 - [SSRS] 子報表 修正,用 ReportViewer 來呈現並紀錄使用方式。

ReportViewer 子報表必須透過 SubreportProcessing Event 來塞 DataSource 進子報表,本篇想記錄的重點
using Dapper;

namespace SubReport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SubReport.子報表.rdlc";
            List<RVMPurch> PurchList = GetRVMPurch();
            // 故意把報表內資料集名稱取的跟 Class 一樣
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource(nameof(RVMPurch), PurchList));
            reportViewer1.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
            reportViewer1.RefreshReport();
        }

        private void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
            string PurNO = e.Parameters["PurNO"].Values[0]?.ToString();
            List<RVMPurchDetail> PurchDetailList = GetRVMPurchDetails(PurNO);
            // 故意把報表內資料集名稱取的跟 Class 一樣
            e.DataSources.Add(new ReportDataSource(nameof(RVMPurchDetail), PurchDetailList));
        }

        #region DB 存取相關
        private string ConnectionString = @"Data Source=.\SQL2017;Initial Catalog=AdventureWorks2017;Integrated Security=True;";

        private List<RVMPurch> GetRVMPurch()
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                string TSQL = @"
                        SELECT 
                          P.* , 
                          E.EmpName , 
                          S.SPLName , 
                          S.Contact , 
                          S.Tel , 
                          S.Fax
                        FROM Purch AS P
                          JOIN Employ AS E ON P.PurEmpNO = E.EmpNO
                          JOIN Supplier AS S ON P.SPLNO = S.SPLNO";

                return conn.Query<RVMPurch>(TSQL).ToList();
            }
        }

        private List<RVMPurchDetail> GetRVMPurchDetails(string purNO)
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                string TSQL = @"
                    SELECT * 
                    FROM PurchDetail 
                    WHERE PurNO = @PurNO";

                object para = new { PurNO = purNO };
                return conn.Query<RVMPurchDetail>(TSQL, para).ToList();
            }
        } 
        #endregion
    }
}

沒有留言:

張貼留言