はじめに
ActiveReportで帳票を作っているときにDetailのFormatイベントにて共通して書きたいコードがでてきた。
イベントに毎回書くと、書き忘れつながるので毎回書かなくても良い実装はできないかと考えました。
環境
.NET Framework C# 7.3
ActiveReport 12.0J
実装方法
共通処理を実施用のベースクラスを作成し、各レポートクラスに継承させることで実装しました。
ReportBase.cs
public class ReportBase : GrapeCity.ActiveReports.SectionReport
{
public ReportBase()
{
this.ReportStart += ReportBase_ReportStart;
}
private void ReportBase_ReportStart(object sender, EventArgs e)
{
foreach (Section section in this.Sections)
{
if (!(section is Detail)) continue;
section.Format += Section_Format;
}
}
private void Section_Format(object sender, EventArgs e)
{
Debug.Print("共通イベント");
}
}
TestReport.cs
public class TestReport : ReportBase
工夫した箇所
ベースのコンストラクタでは継承先のInitializeComponent()が実行されていないのでthis.Sectionsの中身が空になっています。
InitializeComponent()を実行後に
foreach (Section section in this.Sections)
{
if (!(section is Detail)) continue;
section.Format += Section_Format;
}
部分を実施したいため、いったんReportStartにイベントを追加してそのイベント内にて上記のコードを実施するようにしました。