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:
Event throwing in the inner of the buttons’ click event handlers:
Now, if I define an object
I MUST NECESSARILY ADD THE EVENT HANDLER:
If I have no need to handle this event, the only way is to let the event handler code empty:
If I don’t add the event to the object
and I don’t write its empty event handler
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
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