Question : Custom control communicating an event to parent form

I've coded the UI for a control (base class: UserControl) and now need to communicate an event to the parent form.  Obviously because the control could be used in different forms I can't know in advance the name of the form - so how do I generate some event (or message), pass this to the parent and have the parent respond to this?


(In C++ I would just create my own message and use PostMessage to communicate with a parent window)

Answer : Custom control communicating an event to parent form

You need to define your own event and have the parent form subscribe to it. Simple example using standard EventHandler (you'll need to define your own delegate/eventargs class if you want to pass custom information with your event):
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
// user control
    public partial class MyUserControl : UserControl
    {
        public event EventHandler SomethingHappened;

        public MyUserControl()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OnSomethingHappened();
        }

        protected void OnSomethingHappened()
        {
            if (SomethingHappened != null)
                SomethingHappened(this, new EventArgs());
        }
    }


'// parent form
private void Form1_Load(object sender, EventArgs e)
{
    myUserControl1.SomethingHappened += new EventHandler(myUserControl1_SomethingHappened);
}

void myUserControl1_SomethingHappened(object sender, EventArgs e)
{
    MessageBox.Show("Something happened");
}
Random Solutions  
 
programming4us programming4us