Crash893 Crash893 - 1 year ago 113
C# Question

How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?

I have a custom usercontrol and I want to do something relatively simple.

When ever a numeric up down in that usercontrol's value changes, have the main form update a display window.

This is not a problem if the NUD was not in a usercontrol but I can't seem to figure out how to have the event handled by the mainform and not the usercontrol.

Answer Source

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               


UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
    //handle the event 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download