Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I raise an event in a usercontrol and catch it in mainpage?

People also ask

How do you raise an event in C#?

Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.

How do you make the events raised by child controls in a user control available to the host page?

By default, events raised by child controls in a user control are not available to the host page. However, you can define events for your user control and raise them so that the host page is notified of the event. You do this in the same way that you define events for any class.


Check out Event Bubbling -- http://msdn.microsoft.com/en-us/library/aa719644%28vs.71%29.aspx

Example:

User Control

public event EventHandler StatusUpdated;

private void FunctionThatRaisesEvent()
{
    //Null check makes sure the main page is attached to the event
    if (this.StatusUpdated != null)
       this.StatusUpdated(this, new EventArgs());
}

Main Page/Form

public void MyApp()
{
     //USERCONTROL = your control with the StatusUpdated event
     this.USERCONTROL.StatusUpdated += new EventHandler(MyEventHandlerFunction_StatusUpdated);
}

public void MyEventHandlerFunction_StatusUpdated(object sender, EventArgs e)
{
         //your code here
}

Just add an event in your control:

public event EventHandler SomethingHappened;

and raise it when you want to notify the parent:

if(SomethingHappened != null) SomethingHappened(this, new EventArgs);

If you need custom EventArgs try EventHandler<T> instead with T beeing a type derived from EventArgs.


Or if you are looking for a more decoupled solution you can use a messenger publisher / subscriber model such as MVVM Light Messenger here