Custom events (C#)

  • Thread starter Torbjorn Stavas
  • Start date
T

Torbjorn Stavas

I've been trying to use a custom event in one of of my classes but i get a
MethodMissingException when calling it. Been looking at
Http://www.ondotnet.com/pub/a/dotnet/2002/04/15/events.html,
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/
cpconprovidingeventfunctionality.asp, and
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/
cpconeventsdelegates.asp.

I'll show some of the code in my classes;
namespace Rapportering
{
public class TestEventArgs: EventArgs
{
public TestEventArgs()
{
}
}

public delegate void TestEventHandler(Object sender, TestEventArgs e);

public class PanelKeyBNum : System.Windows.Forms.Panel
{
public event TestEventHandler TestEvent;
protected virtual void OnTestEvent(TestEventArgs e)
{
//This call generates a MissingMethodException
TestEvent(this, e);
}

//
// Program logic..
//

private void btnClose_Click(object sender, EventArgs e)
{
OnTestEvent(new TestEventArgs());
}
}
}

Is there anyone that knows why this generates a MissingMethodException? None the examples of
creating custom events in c# has been for CF though, so i suspect that there's something i have missed.

The class PanelKeyBNum displays a panel that lets the user write numbers to some textboxes on a form. I want
to know when the user "closes" (i.e visible=false, since it's a panel) PanelKeyBNum, so that the program knows
that it's time to save the input to the textboxes to some variables in another class.

Any suggestions on why this doesn't work is really appreciated.

//Torbjorn
 
T

Torbjorn Stavas

Mark Arteaga said:
Try adding a check for null in OnTestEvent

protected virtual void OnTestEvent(TestEventArgs e)
{
//This call generates a MissingMethodException
if(TestEvent!=null)
TestEvent(this, e);
}

Ooops, it was null. What does this mean? I have followed the "custom
events" examples, and all the code that is vital (i presume) to the
custom event in my program is listed in my original post. Anyone got
an idea?

//torbjorn
 
T

Torbjorn Stavas

Mark Arteaga said:
Try adding a check for null in OnTestEvent

protected virtual void OnTestEvent(TestEventArgs e)
{
//This call generates a MissingMethodException
if(TestEvent!=null)
TestEvent(this, e);
}

Sorry, my fault. I didn't understand that TestEvent is null when no
one is subscribing to the event. The code works like a charm now.

//Many thanks, Torbjorn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top