Solved

Raising an Event -- Object reference not set to an instance of an object

Posted on 2003-11-06
6
2,628 Views
Last Modified: 2012-05-04
Hello,
I'm getting the error:
System.NullReferenceException: Object reference not set to an instance of an object.
The code is below, and the error is on the line that I've indicated with arrows.
Why is this? I can't see what I'm doing wrong. Is this not how you raise an event?
I practically copied this example http://www.akadia.com/services/dotnet_user_controls.html.
Please help!
Thank you.

//this is my web form
namespace TestWebApp
{
  public class MyWebForm : System.Web.UI.Page
  {
    protected MyControlNS.MyControl MyControl;
    private void Page_Load(object sender, System.EventArgs e)
    {
      MyControl = new MyControlNS.MyControl();
      MyControl.TestEvent();
    }
  }
}

//This is my web control
namespace MyControlNS
{
  public class MyControl : System.Web.UI.WebControls.WebControl
  {
    public delegate void EventHandler(Object sender, EventArgs e);

    public event EventHandler MyEvent;

    public int TestEvent()
    {
      MyEvent(this, new System.EventArgs()); // <---- <---- <----
      return 1;
    }
  }
}
0
Comment
Question by:jini555
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 4

Expert Comment

by:Tonylmiller
ID: 9698128
I normally do it something like this:

this.TextBox1.Leave += new System.EventHandler(this.TextBox2_Leave);

private void maskedTextBox2_Leave(object sender, System.EventArgs e)
{
      //Your code here!
}

0
 
LVL 9

Accepted Solution

by:
tinchos earned 140 total points
ID: 9698591
Hi jini555,

The problem is the following .......

you can raise an event, only when it has a handler associated to it, otherwise, as you said, it will throw the  
"Object reference not set to an instance of an object" exception.

In order to avoid this, you can do the following

if( MyControl.TestEvent != null )
     MyControl.TestEvent();

in this way, you'll first avoid the case when testevent is null (does not have any handler associated).
Besides, what's the use of throw an event if it does not have any handler associated to it.

and will be thrown when it has someone who will listen to it.


Hope this helps!

Tincho
0
 
LVL 9

Expert Comment

by:tinchos
ID: 9698612
Just a quote from Programming C# 2nd Edition (O'Reilly)

Example:


It then notifies the subscribers by firing the OnSecondChange event:

// if anyone has subscribed, notify them
if (OnSecondChange != null)
{
     OnSecondChange(this,timeInformation);
}

If an event has no subscribers registered, it will evaluate to null. The test above checks that
the value is not null, ensuring that there are subscribers before calling OnSecondChange.

Cheers

Tincho
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:jini555
ID: 9699370
tinchos,
thank you VERY MUCH for taking the time to explain clearly. I am at home right now, but when I get into work tomorrow, I will make that small change.
I'll get back to you afterwards.

tonylmiller,
Thank you for your input as well. I wanted to merely understand the bug in my code rather than do it another way. :)
0
 
LVL 9

Expert Comment

by:tinchos
ID: 9700637
Ok,

hope that solves all you need.

Tincho
0
 

Author Comment

by:jini555
ID: 9718694
tincho,
sorry for the delay, something came up and i was away.

anyways, yes, that error is gone now :).


i should note, however, that i could not compile it without removing the "event" keyword. According to this article I just found, (which i think might be the one you quoted)

http://www.ondotnet.com/pub/a/dotnet/2003/06/23/progCsharp3.html?page=3

the "event" keyword prevents another class from accessing the delegate with an operator other than += and -= . So -- I will check for null *inside* my control, rather than from the web form.

Thank you,
-J
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question