Search code examples
c#pie-chart

Set color in pie chart in c#.net


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 ?


Solution

  • "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