1
3

C#でMicrosoft RDLC Report DesingerのDataSetを使用する

Posted at

1. はじめに

  • C#の.NET 6で一覧を表示する帳票を出力したい
  • データベースからではなくオブジェクトから帳票にデータをセットしたい

2. 開発環境

  • C#
  • .NET 6
  • Visual Studio 2022 Community
  • Windows 11
  • Microsoft RDLC Report Desinger 2022
  • ReportViewerCore.WinForms (NuGet)

3. データセットの作成

  • 新規作成からデータセットを追加する
  • データセットにDataTableを追加して、帳票に出力するプロパティを定義しておく
    image.png

4. DTOファイルの作成

* DataTaleの定義を使用したほうがよいかもしれないが、DTOファイルを作成してみる

Sales.cs
[Serializable]
public sealed class Sales
{
    public string Customer { get; }
    public string Price { get; }

    public Sales(string customer, string price)
    {
        Customer = customer;
        Price = price;
    }
}

5. レポートファイルの作成

  • レポートファイルを追加してテーブルを配置する
  • データセットを追加してテーブルにフィールド名を定義する
    image 11.png
    image 12.png

6. Windowsフォームアプリの作成

Form1.cs
using Microsoft.Reporting.WinForms;

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

            // ReportViewerコントロールを追加する
            this.Controls.Add(this.reportViewer1);

            // ReportViewerコントロールにレポートを設定する
            reportViewer1.LocalReport.ReportPath = @"..\..\..\Reports\Report1.rdlc";

            // ディスプレイモードを設定する(Normal/PrintMode)
            reportViewer1.SetDisplayMode(DisplayMode.Normal);

            // テーブルへデータソースを設定する
            var list = new List<Sales>();
            list.Add(new Sales("AAA", "1,000"));
            list.Add(new Sales("BBB", "2,000"));
            list.Add(new Sales("CCC", "3,000"));

            ReportDataSource datasource = new ReportDataSource("Sales", list);
            reportViewer1.LocalReport.DataSources.Clear();
            reportViewer1.LocalReport.DataSources.Add(datasource);

            // レポートをリフレッシュする(これをしないと表示されない)
            reportViewer1.RefreshReport();
        }
    }
}

7. 参考文献

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3