I'm trying to fire an event when button is clicked. I click the button and nothing happens.
The problem is I always get null as EventA
in OnEventA()
:
namespace eventsC
{
public partial class Form1 : Form
{
public event EventHandler EventA;
protected void OnEventA()
{
if (EventA != null)
//never arrives here as EventA is always = null
EventA(this, EventArgs.Empty);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OnEventA();
}
}
}
EDIT:
Based on link from Henk Holterman I tested this code also:
public delegate void Eventhandler(object sender, Eventargs args);
// your publishing class
class Foo
{
public event EventHandler Changed; // the Event
protected virtual void OnChanged() // the Trigger method, called to raise the event
{
// make a copy to be more thread-safe
EventHandler handler = Changed;
if (handler != null)
{
// invoke the subscribed event-handler(s)
handler(this, EventArgs.Empty);
}
}
// an example of raising the event
void SomeMethod()
{
if (...) // on some condition
OnChanged(); // raise the event
}
}
I call OnChanged()
when I click a button but the result is still always the same: EventA = null
.