Solved

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

Posted on 2003-11-06
6
2,586 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
  • 3
  • 2
6 Comments
 
LVL 4

Expert Comment

by:Tonylmiller
Comment Utility
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
Comment Utility
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
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:jini555
Comment Utility
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
Comment Utility
Ok,

hope that solves all you need.

Tincho
0
 

Author Comment

by:jini555
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now