Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?
Posted

Pass the event to the main form.

For e.g.
C#
class UControl : UserControl
{
    public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
    public event ButtonClickedEventHandler OnUserControlButtonClicked;

    public UControl()
    {
        userControlButton.Clicked += new EventHandler(OnButtonClicked);
    }

    private void OnButtonClicked(object sender, EventArgs e)
    {
        if (OnUserControlButtonClicked != null)
            OnUserControlButtonClicked(this, e);
    }
}


Then in your main form, handle this event
C#
public MyForm: Form
{
    public MyForm()
    {
        myControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
    }

    private void OnUCButtonClicked(object sender, EventArgs e)
    {
       //Handle event
    }
}
 
Share this answer
 
v2
Comments
Sascha Lefèvre 28-Apr-15 12:05pm    
5ed!
Abhinav S 28-Apr-15 12:06pm    
Thanks.
C#
public MyForm()
    {
        myControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
    }


An object reference is required for the non static field
 
Share this answer
 
Comments
Sascha Lefèvre 28-Apr-15 12:07pm    
"myControl" stands for the instance of your UserControl. If you named yours differently, put that name in there.

This is not a solution. Please delete it and, if needed, post a comment to Abhinav's answer with the button "Have a Question or Comment?". Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900