I have a problem when trying to raise an event of an object where the type implements an interface (where the event is) form another class.
Here is my code :
The interface IBaseForm
public interface IBaseForm
{
event EventHandler AfterValidation;
}
The Form that implement the interface IBaseForm
public partial class ContactForm : IBaseForm
{
//Code ...
public event EventHandler AfterValidation;
}
My controller : Here where the error occurs
Error message :
The event AfterValidation can only appear on the left hand side of += or -=(except when used from whithin the type IBaseForm)
public class MyController
{
public IBaseForm CurrentForm { get; set; }
protected void Validation()
{
//Code ....
//Here where the error occurs
if(CurrentForm.AfterValidation != null)
CurrentForm.AfterValidation(this, new EventArgs());
}
}
Thanks in advance
You cannot raise an event from outside of the defining class.
You need to create a Raise() method on your interface:
public interface IBaseForm
{
event EventHandler AfterValidation;
void RaiseAfterValidation();
}
public class ContactForm : IBaseForm
{
public event EventHandler AfterValidation;
public void RaiseAfterValidation()
{
if (AfterValidation != null)
AfterValidation(this, new EventArgs());
}
}
And in your controller:
protected void Validation()
{
CurrentForm.RaiseAfterValidation();
}
But it is usually a design smell if you want to trigger an event from outside the defining class... usually there should be some logic in the IBaseForm implementations which triggers the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With