Custom Events must be assigned to or program crashes

  • Thread starter Thread starter Jim
  • Start date Start date
J

Jim

I have extended a DataGrid, and made a KeyInput event so I could handle
keypresses in the grid.
Here's the relevant code:
[in the namespace of the class, but not in the class]
public delegate void KeyboardInputDelegate(Keys keyData);

[class member]
public event KeyboardInputDelegate KeyboardInput;

[overridden function to notify event]
protected override bool ProcessDialogKey(Keys keyData)
{
bool result = base.ProcessDialogKey(keyData);
KeyboardInput(keyData); // <-- tell event subscribers
return result;
}

If I don't create a handler for this event, then the program will crash
when it calls KeyboardInput(keyData);, presumably because it's calling a
function that doesn't exist.
So if a handler has not been assigned, how does one keep the program
from attemptinf to call an unhandled event?

Any help appreciated!
Thanks
 
I have extended a DataGrid, and made a KeyInput event so I could
handle keypresses in the grid.
Here's the relevant code:
[in the namespace of the class, but not in the class]
public delegate void KeyboardInputDelegate(Keys keyData);

[class member]
public event KeyboardInputDelegate KeyboardInput;

[overridden function to notify event]
protected override bool ProcessDialogKey(Keys keyData)
{
bool result = base.ProcessDialogKey(keyData);
KeyboardInput(keyData); // <-- tell event subscribers
return result;
}

If I don't create a handler for this event, then the program
will crash when it calls KeyboardInput(keyData);, presumably
because it's calling a function that doesn't exist.
So if a handler has not been assigned, how does one keep the
program from attemptinf to call an unhandled event?

Any help appreciated!
Thanks

Jim,

if (KeyboardInput != null)
KeyboardInput(keyData); // <-- tell event subscribers
 
If I don't create a handler for this event, then the program
if (KeyboardInput != null)
KeyboardInput(keyData); // <-- tell event subscribers

ah, I had tried if(KeyboardInput.Target != null) but I now see that I
did indeed make a boo boo. I was testing the property of an object that
didn't exist.
Your solution above works like a charm.
Thanks very much, and for such a quick reply as well!!
 

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

Back
Top