There are two crucial differences between overriding and adding an event handler
1) To override you need to be a derived class (obviously) whereas anyone can add an event handler to a control.
2) The base class version of these virtual methods fires the event handlers. So if you need to layer in code in a specific place relative to when the event handlers fire (before or after) overriding is the only sure-fire way of doing this. The Paint event is a great example of this. Normally, people add a paint event handler to "decorate" your control from its standard appearance. You need to make sure the control paints it's appearance before the event handlers run otherwise you will draw over the top of the decorations. So the folllowing is the standard pattern for a custom control
protected override void OnPaint(PaintEv entArgs e)
{
// Do your custom painting here
base.OnPaint(e) ; // this fires thte event handlers
}
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
Hi,
Can someone point me to some good best practices kind of documentation on
use of events compared to method overriding.
Ex. In Windows Forms when should i have an event handler for Paint, and when
should i override OnPaint?
I have to implement added functionality in a child class, and am in two
minds .. to have the parent fire an event, or make the method virtual and
override in the child. Am hoping some reading with description of various
scenerios will increase my understanding and eventually help me make the
decision.
thanx in advance
-bh