Mihai Bratulescu
Mihai Bratulescu

Reputation: 1945

C# Excel Chart can't set serie scale

I'm trying to draw a threshold (1 line from left to right). To do so I add the threshold value twice and the value 0 and 1 for xValues then set the scale of X to be from 0 to 1.

public  static void AddThreshold(Chart xlChart, double value, string name, int color, bool secondary)
        {
            Series series = xlChart.SeriesCollection().NewSeries();
            series.Name = name;
            series.XValues = new List<int>() { 0, 1 }.ToArray();
            series.Values = new List<double>() { value, value }.ToArray();

            Axis xAxis, yAxis;

            if (secondary)
            {
                series.AxisGroup = XlAxisGroup.xlSecondary;

                xAxis = (Axis)xlChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlSecondary);
                yAxis = (Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlSecondary);
            }
            else
            {
                xAxis = (Axis)xlChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
                yAxis = (Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
            }

            xAxis.MinimumScale = 0;//getting COM error here
            xAxis.MaximumScale = 1;

            yAxis.Delete();

            series.ChartType = XlChartType.xlXYScatterLinesNoMarkers;
            series.MarkerSize = 3;
            series.Border.LineStyle = XlMarkerStyle.xlMarkerStyleDash;
            series.Border.Color = color;
        }

But I'm always getting a COM error and can't figure out the problem. To make things more annoying the exact method was working in a different project (don't ask about it because the code there was partially deleted by mistake and I am not rewriting it).

Upvotes: 0

Views: 1298

Answers (1)

Jon Peltier
Jon Peltier

Reputation: 6063

You can't set min and max of an axis if it's not a value type of axis, and only XY Scatter charts have an X axis that is a value axis. You need to specify the chart type of the added series as XY Scatter before setting the axis scale.

So move this:

series.ChartType = XlChartType.xlXYScatterLinesNoMarkers;

above this:

xAxis.MinimumScale = 0;

Upvotes: 2

Related Questions