Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

c# - 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].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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...