473,320 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Null pointer exception for events in usercontrols (C#)

Hi,

I'm writing user controls with custom events.

I have a parent custom event that exposes some abstract methods and
some custom events.

I have also created some new user controls that derive from the parent
custom control and add some text boxes, labels, buttons etc...

So, let's say I created a control with a button in it. I'd want that
when I click on the button the button sends an event to the custon
control and the custon control raises a custom event to the form that
host's it.

Here's an example of my code:

public delegate void PirEventHandler(Object sender, EventArgs e);

public abstract class PirParentCtrl : System.Windows.Forms.UserControl
{
public event PirEventHandler PirEvent;
public event PirEventHandler PirClick;
public event PirEventHandler PirDoubleClick;

...

protected void ThrowEvent(object sender, System.EventArgs e)
{
try
{
PirEvent(this,e);
}
catch (Exception ex)
{
MessageBox.Show(this.Name + " (CustomEvent): " + ex.Message);
}

...
}

And this is a custom control:

public class PirButton : PiranhaControls.PirParentCtrl
{

private DevExpress.XtraEditors.SimpleButton button1;

private System.ComponentModel.Container components = null;

public PirButton()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
...
}

#region Codice generato da Progettazione componenti
private void InitializeComponent()
{
...
}

#endregion

private void button1_Click(object sender, System.EventArgs e)
{
ThrowEvent(sender, e);
}

public override object GetValue()
{
return button1.Text;
}

public override void SetValue(params object[] array)
{
string str=(string)array[0];
button1.Text=str;
}
}

When I try to use this control, it works fine when I use its methods
and properties, but I get a null pointer exception when I click on the
button. The exception is referred to PirEvent as if it was not
instantiated. The fact is that I never instantiate this object as I
thought it is automatically instantiated as soon as the event occurs,
and I don't know how I could even do it.

What am I doing wrong?

Thanks for your help,

Mark Saccomandi
Nov 15 '05 #1
1 7288
Hi Mark,

Your events are not instantiated until somebody adds an event handler to the
event. So the right way to do it, I believe, is to follow the desing pattern
used throughout Windows Forms framework.

1. In your base class declare the events as you do

public event SomethingDoneEventHandler SomethingDone;

If you are not familiar with what this line exactly do you can find that
info in the c# specs for example.

I believe it is a good practice to follow the name convenstion suggested by
MS
- Give the event some name containig *verb* and not containing the word
'Event'.
e.g. SomethingDone
- Name the delegate after the event + 'EventHandler'
e.g. SomethingDoneEventHandler
- Name the event releated data after the event + 'EventArgs'
e.g. SomethingDoneEventArgs
2. Decalre one protected virtual OnXXXX method that raises that event (in
your base class) named after the event with On prefix.

protected virtual OnSomethingDone(SomethingDoneEventArgs e)
{
if(SomethingDone != null)
SomethingDone(this, e);
}

In this way if you want to catch an event in some inherited class you can
simply override the OnXXXX method. Normaly you should call the base.OnXXXX
method to have the event fired. If you want to block the event don't call
the base implementation.

--
HTH
B\rgds
100 [C# MVP]

"Mark" <ms*********@libero.it> wrote in message
news:f1**************************@posting.google.c om...
Hi,

I'm writing user controls with custom events.

I have a parent custom event that exposes some abstract methods and
some custom events.

I have also created some new user controls that derive from the parent
custom control and add some text boxes, labels, buttons etc...

So, let's say I created a control with a button in it. I'd want that
when I click on the button the button sends an event to the custon
control and the custon control raises a custom event to the form that
host's it.

Here's an example of my code:

public delegate void PirEventHandler(Object sender, EventArgs e);

public abstract class PirParentCtrl : System.Windows.Forms.UserControl
{
public event PirEventHandler PirEvent;
public event PirEventHandler PirClick;
public event PirEventHandler PirDoubleClick;

...

protected void ThrowEvent(object sender, System.EventArgs e)
{
try
{
PirEvent(this,e);
}
catch (Exception ex)
{
MessageBox.Show(this.Name + " (CustomEvent): " + ex.Message);
}

...
}

And this is a custom control:

public class PirButton : PiranhaControls.PirParentCtrl
{

private DevExpress.XtraEditors.SimpleButton button1;

private System.ComponentModel.Container components = null;

public PirButton()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
...
}

#region Codice generato da Progettazione componenti
private void InitializeComponent()
{
...
}

#endregion

private void button1_Click(object sender, System.EventArgs e)
{
ThrowEvent(sender, e);
}

public override object GetValue()
{
return button1.Text;
}

public override void SetValue(params object[] array)
{
string str=(string)array[0];
button1.Text=str;
}
}

When I try to use this control, it works fine when I use its methods
and properties, but I get a null pointer exception when I click on the
button. The exception is referred to PirEvent as if it was not
instantiated. The fact is that I never instantiate this object as I
thought it is automatically instantiated as soon as the event occurs,
and I don't know how I could even do it.

What am I doing wrong?

Thanks for your help,

Mark Saccomandi

Nov 15 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream...
5
by: Tony Cheng | last post by:
for (int i=0; i<_request.Form.Count; i++ ) { string key = _request.Form.GetKey(i); if ( !key.Equals("formCode") && !key.Equals("formLanguage") && !key.Equals("__VIEWSTATE") &&...
0
by: Scott McChesney | last post by:
I have a problem I hope you folks can help me with. I have an application that is using a tab-based interface, with the ability for users to drag an item from a ListBox onto the tab control. ...
18
by: Denis Petronenko | last post by:
Hello, in the following code i have segmentaion fault instead of exception. Why? What i must to do to catch exceptions in such situation? Used compiler: gcc version 3.3.6 (Debian 1:3.3.6-13) ...
3
by: Michael | last post by:
Hi, Could you tell me how to under the following statements? Does it mean each and every memory allocation will check all the pointer no matter a null pointer or not? Right? Thanks in advance! ...
1
by: zahidkhan | last post by:
Hi All, Plz help me if you can..... I have a program something like this int main(int argc,char* argv) { try { int* p = NULL;
11
by: MikeT | last post by:
This may sound very elementary, but can you trap when your object is set to null within the object? I have created a class that registers an event from an object passed in the constructor. When...
76
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the...
4
by: Joergen Bech | last post by:
Just out of curiosity: What is your favorite method of making sure that anything that happens on a form, only happens in response to a single, external event? Take the example below. I have made...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.