Search code examples
c#mschart

How to conditionally add data points to a chart rendered with MSChart


I have the sample code below, which renders an MSChart in a Windows Forms Application, here is what the chart looks like:

enter image description here

I would like to add code to conditionally add the data points to the bars, so that if the bar is too short the data point is not added, but if the bar is long enough, then the datapoint is added. In the image of my chart, then the first data point (10) would not be displayed in the chart, but the rest of the data points would be displayed. Can anyone help with this?

        chart1.ChartAreas.Add(new ChartArea());
        chart1.Series[0].IsValueShownAsLabel = true;

        int[] dataset = { 10, 40, 100, 600, 300 };

        foreach (var i in dataset)
        {
            var series1 = chart1.Series[0];
            series1.ChartType = SeriesChartType.StackedBar;

            var index1 = series1.Points.AddY(i);
        }

Solution

  • I found that I was able to make the conditionally make the labels transparent with code like this:

    chart1.ChartAreas.Add(new ChartArea());
    chart1.Series[0].IsValueShownAsLabel = true;
    
    int[] dataset = { 10, 40, 100, 600, 300 };
    var series1 = chart1.Series[0];
    
    foreach (var i in dataset)
    {               
        series1.ChartType = SeriesChartType.StackedBar;
        var index1 = series1.Points.AddY(i);
    }
    
    int j = 0;
    foreach (var point in series1.Points)
    {
        if (dataset[j] > 20)
        {
            point.LabelForeColor = Color.Black;
        }
        else
        {
            point.LabelForeColor = Color.Transparent;
        }
        j++;
    }