Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. "Event" is null while invoking custom event

"Event" is null while invoking custom event

Scheduled Pinned Locked Moved C#
help
11 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Arindam Tewary
    wrote on last edited by
    #1

    Hi All, I am having problem while creating a custom event. My aim is to fire "DataChnaged" event whenever property "SetData" is called in following class defination. The problem is, I am getting a null event in this line "DataChanged(this, e);". Anyone can help me understanding where I am wrong,

    public class DataChangedEventArgs : EventArgs
    {
    private String _strArgVal = "";
    public DataChangedEventArgs(String Value)
    {
    _strArgVal = Value;
    }
    }
    public delegate void DataChangedEventHandler(object sender, DataChangedEventArgs e);
    public class MyUserControlOne
    {
    String DataString = String.Empty;
    public event DataChangedEventHandler DataChanged;
    public MyUserControlOne()
    {
    DataString = "";
    }
    protected virtual void OnDataChanged(DataChangedEventArgs e)
    {
    DataChanged(this, e); //This line gives "Object reference not set to instance of an object."
    }
    public String SetData
    {
    set
    {
    if (value != DataString)
    {
    OnDataChanged(new DataChangedEventArgs("Event Fired !!!"));
    } DataString = value;
    }
    }
    }

    Calling code,

    class Program
    {
    static void Main(string[] args)
    {
    MyUserControlOne o = new MyUserControlOne();
    o.SetData = "ABC";
    }
    }

    Thanks, Arindam D Tewary

    S L 2 Replies Last reply
    0
    • A Arindam Tewary

      Hi All, I am having problem while creating a custom event. My aim is to fire "DataChnaged" event whenever property "SetData" is called in following class defination. The problem is, I am getting a null event in this line "DataChanged(this, e);". Anyone can help me understanding where I am wrong,

      public class DataChangedEventArgs : EventArgs
      {
      private String _strArgVal = "";
      public DataChangedEventArgs(String Value)
      {
      _strArgVal = Value;
      }
      }
      public delegate void DataChangedEventHandler(object sender, DataChangedEventArgs e);
      public class MyUserControlOne
      {
      String DataString = String.Empty;
      public event DataChangedEventHandler DataChanged;
      public MyUserControlOne()
      {
      DataString = "";
      }
      protected virtual void OnDataChanged(DataChangedEventArgs e)
      {
      DataChanged(this, e); //This line gives "Object reference not set to instance of an object."
      }
      public String SetData
      {
      set
      {
      if (value != DataString)
      {
      OnDataChanged(new DataChangedEventArgs("Event Fired !!!"));
      } DataString = value;
      }
      }
      }

      Calling code,

      class Program
      {
      static void Main(string[] args)
      {
      MyUserControlOne o = new MyUserControlOne();
      o.SetData = "ABC";
      }
      }

      Thanks, Arindam D Tewary

      S Offline
      S Offline
      Saksida Bojan
      wrote on last edited by
      #2

      first you need to check if OnDataChanged DataChanged is not null, then throw event. NullReferenceException is thrown, because there isn't any method subscribed to that event

      modified on Monday, March 1, 2010 1:40 PM

      A 1 Reply Last reply
      0
      • A Arindam Tewary

        Hi All, I am having problem while creating a custom event. My aim is to fire "DataChnaged" event whenever property "SetData" is called in following class defination. The problem is, I am getting a null event in this line "DataChanged(this, e);". Anyone can help me understanding where I am wrong,

        public class DataChangedEventArgs : EventArgs
        {
        private String _strArgVal = "";
        public DataChangedEventArgs(String Value)
        {
        _strArgVal = Value;
        }
        }
        public delegate void DataChangedEventHandler(object sender, DataChangedEventArgs e);
        public class MyUserControlOne
        {
        String DataString = String.Empty;
        public event DataChangedEventHandler DataChanged;
        public MyUserControlOne()
        {
        DataString = "";
        }
        protected virtual void OnDataChanged(DataChangedEventArgs e)
        {
        DataChanged(this, e); //This line gives "Object reference not set to instance of an object."
        }
        public String SetData
        {
        set
        {
        if (value != DataString)
        {
        OnDataChanged(new DataChangedEventArgs("Event Fired !!!"));
        } DataString = value;
        }
        }
        }

        Calling code,

        class Program
        {
        static void Main(string[] args)
        {
        MyUserControlOne o = new MyUserControlOne();
        o.SetData = "ABC";
        }
        }

        Thanks, Arindam D Tewary

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        Arindam Tewary wrote:

        if (value != DataString) { OnDataChanged(new DataChangedEventArgs("Event Fired !!!")); } DataString = value;

        furthermore it is wrong to throw the event BEFORE the data change has occurred. A delegate is likely to read SetData to find out what the new data value is, it should not get the old value instead. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
        All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


        A 1 Reply Last reply
        0
        • S Saksida Bojan

          first you need to check if OnDataChanged DataChanged is not null, then throw event. NullReferenceException is thrown, because there isn't any method subscribed to that event

          modified on Monday, March 1, 2010 1:40 PM

          A Offline
          A Offline
          Arindam Tewary
          wrote on last edited by
          #4

          Thanks Saksida. As per your comment I noticed I have not provided any method which subscribes to the event. Now after I have written a "MyUserControlOne_DataChanged" method and its working nicely. Thank you very much for poiting me the mistake. Now this is working nicely !

          public class DataChangedEventArgs : EventArgs
          {
              private String \_strArgVal = "";
              public DataChangedEventArgs(String Value)
              {
                  \_strArgVal = Value;
              }
          }
          public delegate void DataChangedEventHandler(object sender, DataChangedEventArgs e);
          public class MyUserControlOne
          {
              String DataString = String.Empty;
              private bool isEventWorking = false;
              public event DataChangedEventHandler DataChanged;
              public MyUserControlOne()
              {
                  DataString = "";
                  this.DataChanged += new DataChangedEventHandler(MyUserControlOne\_DataChanged);
              }
          
              protected void MyUserControlOne\_DataChanged(object sender, DataChangedEventArgs e)
              {
                  isEventWorking = true;
              }
              protected virtual void OnDataChanged(DataChangedEventArgs e)
              {
                  DataChanged(this, e);
              }
              public String SetData
              {
                  set
                  {
                      if (value != DataString)
                      {
                          OnDataChanged(new DataChangedEventArgs("Event Fired !!!"));
                      } DataString = value;
                  }
              }
              public bool EventWorking
              {
                  get { return isEventWorking; }
              }
          }
          

          calling code:

              static void Main(string\[\] args)
              {
                  MyUserControlOne o = new MyUserControlOne();
                  o.SetData = "ABC";
                  o.SetData = "ABCD";
                  o.SetData = "ABCD";
                  Console.WriteLine(o.EventWorking);
              }
          

          Thanks, Arindam D Tewary

          OriginalGriffO 1 Reply Last reply
          0
          • L Luc Pattyn

            Arindam Tewary wrote:

            if (value != DataString) { OnDataChanged(new DataChangedEventArgs("Event Fired !!!")); } DataString = value;

            furthermore it is wrong to throw the event BEFORE the data change has occurred. A delegate is likely to read SetData to find out what the new data value is, it should not get the old value instead. :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


            I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
            All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


            A Offline
            A Offline
            Arindam Tewary
            wrote on last edited by
            #5

            Hi Luc, Thank you very much for your valuable input. Its great to get some input from MVPs :) Thats surely bad design. I would change that immediately. As I was digged into that "NullException", so I overlooked that. Please if you want to provide any other input also, although origianl problem is solved, please provide.

            Thanks, Arindam D Tewary

            D 1 Reply Last reply
            0
            • A Arindam Tewary

              Thanks Saksida. As per your comment I noticed I have not provided any method which subscribes to the event. Now after I have written a "MyUserControlOne_DataChanged" method and its working nicely. Thank you very much for poiting me the mistake. Now this is working nicely !

              public class DataChangedEventArgs : EventArgs
              {
                  private String \_strArgVal = "";
                  public DataChangedEventArgs(String Value)
                  {
                      \_strArgVal = Value;
                  }
              }
              public delegate void DataChangedEventHandler(object sender, DataChangedEventArgs e);
              public class MyUserControlOne
              {
                  String DataString = String.Empty;
                  private bool isEventWorking = false;
                  public event DataChangedEventHandler DataChanged;
                  public MyUserControlOne()
                  {
                      DataString = "";
                      this.DataChanged += new DataChangedEventHandler(MyUserControlOne\_DataChanged);
                  }
              
                  protected void MyUserControlOne\_DataChanged(object sender, DataChangedEventArgs e)
                  {
                      isEventWorking = true;
                  }
                  protected virtual void OnDataChanged(DataChangedEventArgs e)
                  {
                      DataChanged(this, e);
                  }
                  public String SetData
                  {
                      set
                      {
                          if (value != DataString)
                          {
                              OnDataChanged(new DataChangedEventArgs("Event Fired !!!"));
                          } DataString = value;
                      }
                  }
                  public bool EventWorking
                  {
                      get { return isEventWorking; }
                  }
              }
              

              calling code:

                  static void Main(string\[\] args)
                  {
                      MyUserControlOne o = new MyUserControlOne();
                      o.SetData = "ABC";
                      o.SetData = "ABCD";
                      o.SetData = "ABCD";
                      Console.WriteLine(o.EventWorking);
                  }
              

              Thanks, Arindam D Tewary

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #6

              It is worth changing your code slightly to cope with the case when you have no handler - if you think about it not handling an event is not an error, it is perfectly normal. As such, it should not throw an exception.

              Arindam Tewary wrote:

                  protected virtual void OnDataChanged(DataChangedEventArgs e)
                  {
                      DataChanged(this, e);
                  }
              

              If you change your code to:

                  protected virtual void OnDataChanged(DataChangedEventArgs e)
                     {
                     EventHandler eh = DataChanged;
                     if (eh != null)
                        {
                        eh(this, e);
                        }
                     }
              

              Then a potential source of run time exception is removed. (The load of "eh" is to handle the admittedly rare case when the handler is removed between the test and the execution)

              You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              A S 2 Replies Last reply
              0
              • OriginalGriffO OriginalGriff

                It is worth changing your code slightly to cope with the case when you have no handler - if you think about it not handling an event is not an error, it is perfectly normal. As such, it should not throw an exception.

                Arindam Tewary wrote:

                    protected virtual void OnDataChanged(DataChangedEventArgs e)
                    {
                        DataChanged(this, e);
                    }
                

                If you change your code to:

                    protected virtual void OnDataChanged(DataChangedEventArgs e)
                       {
                       EventHandler eh = DataChanged;
                       if (eh != null)
                          {
                          eh(this, e);
                          }
                       }
                

                Then a potential source of run time exception is removed. (The load of "eh" is to handle the admittedly rare case when the handler is removed between the test and the execution)

                You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                A Offline
                A Offline
                Arindam Tewary
                wrote on last edited by
                #7

                Hi OriginalGriff, You are very much correct. I would be changing my code for sure. Thanks for your comment. Highly appreciate it. :)

                Thanks, Arindam D Tewary

                1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  It is worth changing your code slightly to cope with the case when you have no handler - if you think about it not handling an event is not an error, it is perfectly normal. As such, it should not throw an exception.

                  Arindam Tewary wrote:

                      protected virtual void OnDataChanged(DataChangedEventArgs e)
                      {
                          DataChanged(this, e);
                      }
                  

                  If you change your code to:

                      protected virtual void OnDataChanged(DataChangedEventArgs e)
                         {
                         EventHandler eh = DataChanged;
                         if (eh != null)
                            {
                            eh(this, e);
                            }
                         }
                  

                  Then a potential source of run time exception is removed. (The load of "eh" is to handle the admittedly rare case when the handler is removed between the test and the execution)

                  You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                  S Offline
                  S Offline
                  Saksida Bojan
                  wrote on last edited by
                  #8

                  I would use:

                  protected virtual void OnDataChanged(DataChangedEventArgs e)
                  {
                  if (DataChanged != null)
                  DataChanged(this, e);

                  }

                  I think this way it is easier to read and not declaring new variable

                  L 1 Reply Last reply
                  0
                  • S Saksida Bojan

                    I would use:

                    protected virtual void OnDataChanged(DataChangedEventArgs e)
                    {
                    if (DataChanged != null)
                    DataChanged(this, e);

                    }

                    I think this way it is easier to read and not declaring new variable

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #9

                    No, what Griff gave you is the correct way to do things; there is a (probably small) probability that another thread could remove the content of the event between your code checking it for null, and your code using it. A local copy fixes that. :)

                    Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                    I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
                    All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


                    S 1 Reply Last reply
                    0
                    • L Luc Pattyn

                      No, what Griff gave you is the correct way to do things; there is a (probably small) probability that another thread could remove the content of the event between your code checking it for null, and your code using it. A local copy fixes that. :)

                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                      I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
                      All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


                      S Offline
                      S Offline
                      Saksida Bojan
                      wrote on last edited by
                      #10

                      tham. Now i see the problem. It was same example in a book i was reading. Maybe it is time to burn that book

                      1 Reply Last reply
                      0
                      • A Arindam Tewary

                        Hi Luc, Thank you very much for your valuable input. Its great to get some input from MVPs :) Thats surely bad design. I would change that immediately. As I was digged into that "NullException", so I overlooked that. Please if you want to provide any other input also, although origianl problem is solved, please provide.

                        Thanks, Arindam D Tewary

                        D Offline
                        D Offline
                        DaveyM69
                        wrote on last edited by
                        #11

                        There are many articles and blogs that deal with events but most are a little overwhelming initialy. I wrote this[^] article to provide a gentle tutorial which you may find useful.

                        Dave
                        Tip: Passing values between objects using events (C#)
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                        Why are you using VB6? Do you hate yourself? (Christian Graus)

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups