LoginSignup
1
4

More than 1 year has passed since last update.

C# UserControl(子)からForm(親)へのイベント通知

Last updated at Posted at 2022-09-10

UserControl(子)でイベントが発火して、Form(親)で受け取りたい場合の自分用備忘録です。

UserControlとFormのデザイン

実行.png
※ 黄色い範囲と内側のボタンがユーザーコントロール

UserControlとFormのコード

UserControl側(イベント発生側)

    public partial class MyUserControl : UserControl
    {
        // -------------------------------------------------------------
        // デリゲートイベントの定義
        // -------------------------------------------------------------
        // 親へイベントをデリゲートするためのイベントハンドラを定義
        public delegate void OnFruitSelectedEventHandler(OnFruitSelectedEventArgs e);
        public event OnFruitSelectedEventHandler OnFruitSelected;
 
       // デリゲートの引数を定義
        public class OnFruitSelectedEventArgs : EventArgs
        {
            public string strFruit;
        }

        // -------------------------------------------------------------
        // 初期化とロード
        // -------------------------------------------------------------
        public MyUserControl()
        {
            InitializeComponent();
        }

        // -------------------------------------------------------------
        // イベントの発火
        // -------------------------------------------------------------
        private void buttonApple_Click(object sender, EventArgs e)
        {
            // イベントの引数を設定
            var arg = new OnFruitSelectedEventArgs { 
                strFruit = "りんご"
            };
            // イベントの発火
            OnFruitSelected(arg);
        }

        private void buttonWatermelon_Click(object sender, EventArgs e)
        {
            // イベントの引数を設定
            var arg = new OnFruitSelectedEventArgs { 
                strFruit = "スイカ" 
            };
            // イベントの発火
            OnFruitSelected(arg);
        }
    }

Form側(イベント受信側)

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

            // ユーザーコントロールで発火するイベントハンドラを追加
            myUserControl.OnFruitSelected += OnFruit_Selected;

        }

        // イベント発火時の処理
        private void OnFruit_Selected(OnFruitSelectedEventArgs e)
        {
            myLabel.Text = e.strFruit;
        }
    }
1
4
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
4