Search code examples
c#winformsdatapoint

How to plot different colour for negative datapoint in line chart c#


I want to create line chart by datagridview I need red colour plot line for negative values and green for positive values. I write the code but I get only green colour for all data points.

foreach (DataGridViewRow row in dgvReport.Rows)
{ 
    decimal val = 0;
    val = Convert.ToDecimal(row.Cells[8].Value.ToString());

    if (val < 0)
    {
        Dchart.Series[0].Color = System.Drawing.Color.Red;
    }

    if (val > 0)
    {
        Dchart.Series[0].Color = System.Drawing.Color.Green;
    }

    Dchart.Series[0].Points.AddXY(row.Cells[0].Value.ToString(), row.Cells[8].Value.ToString());
    Dchart.ChartAreas[0].AxisX.Interval = 3;
}

Solution

  • You need to color each DataPoint individually:

    int index = Dchart.Series[0].Points.AddXY(row.Cells[0].Value,
                                              row.Cells[8].Value);
    DataPoint newPoint = Dchart.Series[0].Points[index];
    newPoint.Color = newPoint.YValues[0] < 0 ? Color.Red : Color.Green;
    

    Note that the color goes into only one line!

    Also note that your conversion orgy isn't really needed..

    Final note: You are adding all your values as strings. This is a serious mistake! Doing so will lose all x-values and result in an uncontrolled default conversion of the y-values.

    Always add all values as numbers or DateTimes!!

    If you find that you need to convert the cell value objects to numbers do so and create the DataPoint as a whole, best including the Color before adding it with series.Add()!