Eliran Ziv Eliran Ziv - 1 year ago 52
C# Question

Dynamically creating charts

I am trying to dynamically create a chart for each drive in the computer, inside a form.

Each chart should be a pie chart that contains the amount of free space (colored green) and used space(colored red) in GBs.

But when I run the following code the only thing I see is blank rectangles with the titles of "C:\", "D:\" and so on.

Here is the code :

public static void DrawCharts()
Chart[] charts = new Chart[DriveInfo.GetDrives().Length];
DriveInfo[] drives = DriveInfo.GetDrives();
for (int i = 0; i < drives.Length; i++)
charts[i] = new Chart();
charts[i].Palette = ChartColorPalette.BrightPastel;
charts[i].Series[0].ChartType = SeriesChartType.Pie;
charts[i].Location = new System.Drawing.Point(20 + i * 231, 30);
charts[i].Size = new System.Drawing.Size(230, 300);
DataPoint d = new DataPoint();
d.XValue = 1;
double[] p = { (double)drives[i].TotalFreeSpace / 1000000000 };
d.YValues = p;
d.Color = System.Drawing.Color.YellowGreen;
d.Label = "Free Space";
d.Label = "Used Space";
d.XValue = 2;
double[] a = { (double)((drives[i].TotalSize - drives[i].TotalFreeSpace) / 1000000000) };
d.YValues = a;
d.Color = System.Drawing.Color.Red;


Answer Source

You are almost there.

But the most basic thing you need to add to a dynamically created chart..:

charts[i] = new Chart();

..is a ChartArea:

charts[i].ChartAreas.Add("CA1"); // pick your name!

Without it no Series can display..

Use it to style the axis with TickMarks, GridLines or Labels or to set Minima and Maxima and Intervals. Well, at least for most other ChartTypes; Pies don't need any of this anyway..

Note that you can have several ChartAreas in one Chart.

Also note that it still will display nothing until at least one Series has at least one DataPoint..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download