When should we call base.OnPaint() when we override OnPaint?

You are not overriding the OnPaint() method. You are just subscribing to Paint event, so you should not call base.OnPaint().
You should (could) only call base.OnPaint() when you override the OnPaint() method of the form:

protected override OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    // ... other drawing commands
}

The OnPaint method on Windows Forms controls actually raises the Paint event of the control and also draws the control surface. By calling the base form's OnPaint method in the Paint event handler, you actually are telling the form to call the Paint handler again and again, and so you will fall in an infinite loop, and hence the StackOverflowException.

When you override the OnPaint method of a control, usually you should call the base method, to let the control draw itself and also call the event handlers subscribed to Paint event. If you do not call the base method, some control aspects will not be drawn, and no event handler will be called.


The base.OnPaint(e) method raises the Paint event, so your Form1_Paint method is called inside base.OnPaint. This results in an infinite loop and eventually a StackOverflowException.

The correct thing would be to override the OnPaint method:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    //custom painting here...
}

For more info, see this MSDN link.


from the code above You're not overriding the OnPaint method, you're actually handling the paint event, and, of course, if you try to paint it again inside the handler you get an infinite loop.

Tags:

C#

Winforms