Xantham
Xantham

Reputation: 1899

MSChart not initializing axis bounds until drawn

MSChart in my C# program is acting in a peculiar fashion. It will not actually have its axes' Maximum and Minimum sizes initialized until after it is drawn. Observe the code snippet below.

void drawChart
{
    Chart tempChart = new Chart();
    Series series1 = new Series();

    /*  Additional chart setup removed for clarity  */

    series1.Points.AddXY(0, 4);
    series1.Points.AddXY(10, 2);
    series1.Points.AddXY(5, 20);
    series1.Points.AddXY(8, 9);
    series1.Points.AddXY(15, 30);

    double max = tempChart.ChartAreas["ChartArea1"].AxisX.Maximum;
    Console.WriteLine(max.ToString());      //Output:  NaN

    MemoryStream theStream = new MemoryStream();
    tempChart.SaveImage(theStream, ChartImageFormat.Png);

    max = tempChart.ChartAreas["ChartArea1"].AxisX.Maximum;
    Console.WriteLine(max.ToString());      //Output:  17
}

As shown in the snippet, when I ran code in my program, the AxisX.Maximum was NaN before I wrote its image to a MemoryStream, but the appropriate 17 afterwards.

Why is it doing this, and more imporantly, how can I force it to initialize AxisX.Maximum without writing to a stream. I do want it to be drawn to an image, but I need to do setup on the chart that requires knowing the autosize bounds before it is rasterized.

Upvotes: 1

Views: 434

Answers (1)

zeFrenchy
zeFrenchy

Reputation: 6591

You can force the chart to compute the axis min and max with

tempChart.ChartAreas["ChartArea1"].RecalculateAxesScale();

Upvotes: 2

Related Questions