Mong Zhu Mong Zhu - 16 days ago 5
C# Question

At which point in time is the series colour initialised in a chart graph

I use

Chart
to draw a graph with 2 lines. Now my aim is to set the
LineColor
of the
MajorGrid
of the second Y-axis to the color of the corresponding line. Here is my code:

public partial class Form1 : Form
{

List<double> values_1 = new List<double>();
List<double> values_2 = new List<double>();

public Form1()
{
InitializeComponent();

make_values();

for (int i = 0; i < values_1.Count; i++)
{
chart1.Series[0].Points.AddY(values_1[i]);
}

for (int i = 0; i < values_2.Count; i++)
{
chart1.Series[1].Points.AddY(values_2[i]);
}

// set the colour of grid to corresponding line
chart1.ChartAreas[0].AxisY2.MajorGrid.LineColor = chart1.Series[1].Color;

}

private void Form1_Load(object sender, EventArgs e)
{

}

public void make_values()
{
for (int i = 0; i < 600; i++)
{
values_1.Add(Math.Sin(i / 60.0));
values_2.Add(Math.Cos(i / 60.0));
}

}
}


Since the colours are chosen automatically for the 2 different series I though I could just grab the colour. But when debugging I see that the colour is (0,0,0):

enter image description here

So the grid colour does not change. But the colour of the second series is not (0,0,0) as can be seen when the window is loaded!:

enter image description here

If I force and set manually the colours of the 2 series before that. Everything works fine, and the grid gets the corresponding colour.

Does anyone know at which point in time I would have to grab the colour of the series to get the real value?

TaW TaW
Answer

To access the Series Colors you need to call ApplyPaletteColors. This is necessary when you want to use them for other elements or when custom drawing. You should also call it again after changing the palette..

chart1.ApplyPaletteColors();

MSDN:

Remarks

When the Chart colors are automatically assigned at run time, there is no way to know what the colors will be prior to the time when the chart rendered; the Color property of an automatically assigned value will return Empty at this time.

If you call the ApplyPaletteColors method, the colors for the series and the data points will be set, which allows for programmatic access.

Comments