Unable to get Chart Paint events

I want to do some custom drawing in a chart. To do this I need to access the ChartGraphics Object referenced by the PrePaint and PostPaint Chart events. Are these events working? So far I have tried subscribing to the event at multiple points in the report generation, without success. Here an example:

private void Plot_1BeforePrint(object sender, EventArgs e)
{ 
  Plot_1.Chart.PostPaint += OnPostPaint;
  Plot_1.Chart.Invalidate(); // Is supposed to repaint the chart and call PrePaint, Paint, and PostPaint events.
}

private void OnPostPaint(object sender, ChartPaintEventArgs e)
{
  Console.WriteLine("I never see this line.");
  var cg = e.ChartGraphics; // This is the thing I want!
}

Any help would be greatly appreciated. Thanks!

Comments

  • Hello!

    I have managed to reproduce this behaviour, created an issue and forwarded it to our developers; please expect fixes in future versions of FastReport .NET.

  • In FastReport .NET, event subscriptions to the BeforePrint event are bound to the chart instance from the report template. During the Report.Prepare() stage, FastReport builds the prepared pages (PreparedPages), but does not yet render them. Rendering takes place later — when viewing in Preview or during export, where the prepared page already contains a new cloned instance of the chart, which has no attached PrePaint/PostPaint event handlers.

    To resolve this issue, render the chart with custom post-rendering to a Bitmap in the BeforePrint event and pass it to the PictureObject:

    private void DataBand1_BeforePrint(object sender, EventArgs e)
    {
    using var chart = new System.Windows.Forms.DataVisualization.Charting.Chart { Width = 600, Height = 300 };
    chart.ChartAreas.Add(‘Main’);
    var s = chart.Series.Add(‘S1’);
    s.Points.AddXY(‘A’, 100);
    s.Points.AddXY(‘B’, 200);
    using var bmp = new Bitmap(chart.Width, chart.Height);
    chart.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
    // Custom drawing on top of the chart
    using (var g = Graphics.FromImage(bmp))
    using (var pen = new Pen(Color.Red, 2))
    {
    g.DrawLine(pen, 50, 80, bmp.Width - 50, 80);
    }
    using var ms = new MemoryStream();
    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    Picture1.SetImageData(ms.ToArray());
    }
    
This discussion has been closed.