0

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;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Venkat
  • 15
  • 7

1 Answers1

3

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()!

TaW
  • 53,122
  • 8
  • 69
  • 111