Dynamically creating charts

2019-01-29 01:20发布

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].Titles.Add(drives[i].Name);
            charts[i].Series.Add("Storage");
            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";
            charts[i].Series[0].Points.Add(d);
            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;
            charts[i].Series[0].Points.Add(d);
            Form1.tabs.TabPages[1].Controls.Add(charts[i]);
            charts[i].Invalidate();
        }
    }

Thanks.

标签: c# charts
1条回答
神经病院院长
2楼-- · 2019-01-29 01:53

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..

查看更多
登录 后发表回答