StepUp
StepUp

Reputation: 38094

Why is subscribed event always null?

I declare a subscription to event in:

public class MainClass
{
    public void btndel_bar_Click(object sender, RoutedEventArgs e)
    {
        SomeClass sc = new SomeClass();
        sc.FieldUpdate += new SomeClass.FieldUpdateHandler(sc_FieldUpdate);
    }

    void sc_FieldUpdate(object sender, ValueEventArgs e)
    {
        MessageBox.Show(e.Smth_property);
    }
}

And here is I want to listen event:

public class Someclass
{
    public delegate void FieldUpdateHandler(object sender, ValueEventArgs e);
    public event FieldUpdateHandler FieldUpdate;

    void Somemethod()
    {
        string str = "Steel";
        ValueEventArgs args = new ValueEventArgs(str);
        FieldUpdate(this, args);   
    }
}

A class which carries data:

public class ValueEventArgs : EventArgs
{
    private string smth;

    public ValueEventArgs(string smth)
    {
        this.smth = smth;
    }

    public string Smth_property
    {
        get { return smth; }
    }
}

I always have FieldUpdate=null. How to solve it?

Upvotes: 0

Views: 2246

Answers (3)

StepUp
StepUp

Reputation: 38094

I've read articles about delegates and events and after reading I always I thought to make all operations again. I did all over again and it works! Consequently I done something wrong when I did at the beginning of.

Upvotes: 0

Anirudha
Anirudha

Reputation: 32797

The moment you create the object of SomeClass your event would get reinitialized.

Make your event a static so that multiple objects of SomeClass would share it

public static event FieldUpdateHandler FieldUpdate;

Upvotes: 0

SLaks
SLaks

Reputation: 887385

You're calling Somemethod() in the constructor, before the calling code gets a chance to add the event handler.
Therefore, the event is still null.

Upvotes: 4

Related Questions