Search code examples
c#winformsrangemschartseries

Range bar in MS Chart


I want to generate bars like in link: enter image description here

However, I get this error:

enter image description here

Here is the code I use:

        // AxisY
        chart1.ChartAreas.Add(CA);
        chart1.ChartAreas[1].AxisY.MajorGrid.Enabled = false;
        chart1.ChartAreas[1].AxisY.Interval = 1;

        // AxisX
        chart1.ChartAreas[1].AxisX.ScrollBar.Enabled = true;
        chart1.ChartAreas[1].AxisX.ScaleView.Zoomable = true;
        chart1.ChartAreas[1].AxisX.MajorGrid.Enabled = false;
        chart1.ChartAreas[1].AxisX.LabelStyle.Format = "yyyy-MM-dd hh:mm:ss";

        chart1.ChartAreas[1].AxisX.Interval = 0;
        chart1.ChartAreas[1].AxisX.IntervalType = DateTimeIntervalType.Years;

        minDate = new DateTime(2016, 01, 01, 00, 00, 00, 000);
        maxDate = new DateTime(2016, 12, 01, 00, 00, 00, 000); // or DateTime.Now;

        chart1.ChartAreas[1].Axes[0].Enabled = AxisEnabled.False;
        chart1.ChartAreas[1].Axes[1].Enabled = AxisEnabled.False;

        chart1.ChartAreas[1].BackColor = Color.Transparent;
        chart1.ChartAreas[1].Position.Height = 100;
        chart1.ChartAreas[1].Position.Width = 100;
        chart1.ChartAreas[1].InnerPlotPosition.Height = 90;
        chart1.ChartAreas[1].InnerPlotPosition.Width = 80;
        chart1.ChartAreas[1].InnerPlotPosition.X = 10;

        var series2 = new Series
        {
            Name = "S2",
            Color = Color.Black,
            ChartType = SeriesChartType.RangeBar,
            YValueType = ChartValueType.Auto,
            XValueType = ChartValueType.Auto
        };

        var values2 = new DateTime[3];
        values2[0] = minDate.AddMonths(2);
        values2[1] = minDate.AddMonths(4);
        values2[2] = minDate.AddMonths(6);

        series2.Points.AddXY(1, values2[1], values2[2]);

        series2["PointWidth"] = ".25";

        chart1.Series.Add(series2);

The bottom axis is a date time. the left axis is fixed and has words as labels. I need to show gap in data.


Solution

  • Yes, this looks weird at first glance and the error message is not pointing you in the right direction.

    The reason is that you try to add points to the series before you have added the series to the chart.

    RangeBar cannot be combined with any other chart type except bar-type charts.

    Therefore (?) the chart can't check if the points are actually added in a valid way and instead of saying so it claims that your series accepts only one y-value.

    Solution: Simply add the series2 to the Chart before adding any DataPoints and all is well..