Launch event in the form from a user control

0

I have a form that will contain several copies of a user control, what I want to do is that when within one of those user controls a button is clicked, an event of the form that contains it is launched.

I thought about saving a reference of the form in the constructor of the user control and thus be able to call any method of that form, but it seems to me an inelegant solution.

I would appreciate if someone can indicate to me some more elegant way of doing this.

    
asked by U. Busto 06.02.2018 в 16:35
source

1 answer

0

You could do it by propagating events:

public partial class UserControl1 : UserControl
    {

        public delegate void ButtonClick(object sender, EventArgs e);
        public event ButtonClick OnButtonClick;
        public UserControl1()
        {
            InitializeComponent();

            button1.Click += new EventHandler((sender, args) =>
            {
                OnButtonClick?.Invoke(this, null);
            });
        }
    }



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

            UserControl1 usrCtrl = new UserControl1();
            usrCtrl.OnButtonClick += UsrCtrl_OnButtonClick;
            this.Controls.Add(usrCtrl);
        }

        private void UsrCtrl_OnButtonClick(object sender, EventArgs e)
        {
            MessageBox.Show("Click en boton dentro del usercontrol");
        }
    }
    
answered by 29.05.2018 в 17:05