I understand how i create properties for a usercontrol but im having difficulty finding info on how you would create a "event" for user control so i can trigger code to run on the form and not in the control itself
anyone have a example?
thanks
Printable View
I understand how i create properties for a usercontrol but im having difficulty finding info on how you would create a "event" for user control so i can trigger code to run on the form and not in the control itself
anyone have a example?
thanks
The fact that it's a UserControl is irrelevant. It's just a class. You add events to any class the exact same way:To raise the event you call the OnMyEvent method:CSharp Code:
public event EventHandler MyEvent; protected virtual void OnMyEvent(EventArgs e) { if (this.MyEvent != null) { this.MyEvent(this, e); } }If you need to pass data to the event handlers then you'd use the generic EventHandler delegate:CSharp Code:
this.OnMyEvent(EventArgs.Empty);I've used CancelEventArgs there as an example but you can use any appropriate class that inherits EventArgs, either from the Framework or of your own creation. When you raise the event you obviously need to pass an object of that type to the OnMyEvent method.CSharp Code:
public event EventHandler<CancelEventArgs> MyEvent; protected virtual void OnMyEvent(CancelEventArgs e) { if (this.MyEvent != null) { this.MyEvent(this, e); } }
One final note. I've also just used "MyEvent" as an example. You'd name your event something more appropriate and then name the method that raises it to match. If you look through the MSDN documentation you'll see that almost all events are raised by a method with the same name prefixed with "On".
Quote:
Originally Posted by jmcilhinney
Thanks
It looked a little complex at first but actually its pretty simple. Im still shakey on some of the more complex concepts of Object oriented programing in general but i think im getting there slowly.
again thanks for the pointer.