I am trying to create a simple pie chart using data extracted from a database in C#.NET. I have used following codes-
string[] xAxis = { "Banana", "Mango", "Apple" };
double BananaPercentage= 40;
double MangoPercentage= 30;
double ApplePercentage = 30;
double[] Percentage = { BananaPercentage, MangoPercentage, ApplePercentage };
Color[] PieColors = { Color.Green, Color.Red, Color.Gray };
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
//chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
It shows pie chart with correct values. But when I try to assign specific color for Banana(green), Mango(red) and Apple(Gray), it shows error "index was out of range. must be non-negative.....". Could anyone give me any hints what is wrong here ?
"index was out of range..." is because of chart1.Series[0].Points[0]
, especially .Points[0]
. Not because of PieColors[0]
. You should add some Points before, if you want to use them further or if you want to change their colors. For example :
int index = chart1.Series[0].Points.AddXY(x, y);
and then you can do like:
chatr1.Series[0].Points[index].Color = PieColors[0]; //or whatever color
In your case, the problems is, you bind points to chart1.Series[0].Points
after you try to assign Point's color. Try to change this :
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
To
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points[1].Color = PieColors[1];
chart1.Series[0].Points[2].Color = PieColors[2];
If you want to change Series color, not Point, you can write something like:
chart1.Series[0].Color = Color.Red; //or any other color, maybe from PieColor
this.CategoryGraphChart.Series["Categories"].Points.AddXY(test.ToString() + "(" + number + ")", number);
CategoryGraphChart.Palette = ChartColorPalette.None;
CategoryGraphChart.PaletteCustomColors = new Color[] { Color.BlanchedAlmond, Color.Blue, Color.Yellow };
This code will work...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.