Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Possible C# bug in a definition and use of an event/eventhandler 2

Status
Not open for further replies.

polocar

Programmer
Sep 20, 2004
89
IT
Hi,
I have defined a class derived from Panel class (let’s call it MyPanel).
It contains three buttons, called btn1, btn2 and btn3.
I have defined an event called BtnClicked, and I have thrown it in the code of btn1_Click, btn2_Click and btn3_Click (in practise, it raises when the user clicks on everyone of the three buttons).

Definition of the event:

Code:
public event EventHandler BtnClicked;

Event throwing in the inner of the buttons’ click event handlers:

Code:
void btn1_Click(object sender, EventArgs e)
{
    BtnClicked(sender, e);
}

void btn2_Click(object sender, EventArgs e)
{
    BtnClicked(sender, e);
}

void btn3_Click(object sender, EventArgs e)
{
    BtnClicked(sender, e);
}

Now, if I define an object

Code:
MyPanel myPanel = new MyPanel();

I MUST NECESSARILY ADD THE EVENT HANDLER:

Code:
myPanel.BtnClicked += new EventHandler(myPanel_BtnClicked);

If I have no need to handle this event, the only way is to let the event handler code empty:

Code:
void myPanel_BtnClicked(object sender, EventArgs e)
{

}

If I don’t add the event to the object

Code:
myPanel.BtnClicked += new EventHandler(myPanel_BtnClicked);

and I don’t write its empty event handler

Code:
void myPanel_BtnClicked(object sender, EventArgs e)
{

}

and I click on one of the three buttons, the compiler raises the following error: “Reference to an object not set to an object instance” (I hope to have translated correctly the error from italian).

It’s very strange, because if I define an object of any system class (in example Panel, TextBox, Button, etc.), I don’t need to add all its events (and declare all their handlers, empty if I don’t need them)!!!
What do you think about? Can it be considered a C# bug?

Thank you very much
 
when you define your event in your panel you have to add a handler to it. I usually create a crap handler

this.ButtonClicked += new EventHandler(DoNothing);

private void DoNothing(object sender, EventArgs e);

This way your panel won't throw this error anymore. It is a bit strange that you have to do this but it's better for your panel to handle this rather than the calling code.
 
You could also clean this up by changing how you call BtnClicked in each of the three button events. If you change it to be the following it should clear it up.:
Code:
void btn3_Click(object sender, EventArgs e)
{
    if( BtnClicked != null)
    {
        BtnClicked(sender, e);
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top