我正在尝试在 .NetForms 中创建一个应用程序,在其中从文件中读取数据,然后使用该数据截断图表

问题描述 投票:0回答:1

目前我正在从 csv 文件读取数据并将其显示在一种表单的文本框中。然后,我的目标是将这些数据传递到另一种形式,在其中我可以创建一个可视化的柱形图,其中种族是 X 值,每小时工资是 Y 值。我尝试包含一个组合框,用户可以在其中选择年份来过滤图表。

CSV:https://www.data.gov.uk/dataset/14fb9401-a320-4633-b1f6-b82f77c5d84b/average-hourly-pay-by-ethnicity

问题:即使在调试时,所有 10 个项目都存在,我在条形图上也无法获得超过一个条形。该图表显示第一个种族“亚洲人”,然后是薪酬,而我希望它显示所有 10 个种族。 enter image description here

我尝试了很多创建和填充图表的方法,但没有成功,你们能给我一些建议吗? (我试图使代码尽可能简单,它不一定是最高标准)

这是我读取 csv 并存储数据的第一个表单,我可以选择在包含的文本框中显示数据。

namespace AS2_U17_5th
{
    public partial class Form1 : Form
    {
        // Declaring datalist at the class level
        public static List<DataItems> datalist = new List<DataItems>();

        public Form1()
        {
            InitializeComponent();
            ReadDataFromCSV();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // call the display data function
            LoadDataIntoListBox();
        }

        // Removed the redundant declaration of datalist here
        public void LoadDataIntoListBox()
        {
            try
            {
                foreach (DataItems d in datalist)
                {
                    TBData.AppendText($"{d.Year} {d.Ethnicity} {d.HourlyWage}\r\n");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred while loading data into the ListBox {ex.Message}");
            }
        }

        // Method to read data from CSV file
        public static void ReadDataFromCSV()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("average-hourly-pay.csv"))
                {
                    // Skip header line
                    streamReader.ReadLine();

                    // Looping over remaining lines
                    while (!streamReader.EndOfStream)
                    {
                        string line = streamReader.ReadLine();
                        string[] data = line.Split(',');

                        
                        
                            // Parsing data
                            int year;
                            if (!int.TryParse(data[0], out year))
                            {
                                // Log error and continue to next line
                                continue;
                            }

                            string ethnicity = data[1];

                            double hourlyWage;
                            if (!double.TryParse(data[2], out hourlyWage))
                            {
                                // Log error and continue to next line
                                continue;
                            }

                            // make a new object
                            DataItems item = new DataItems
                            {
                                Year = year,
                                Ethnicity = ethnicity,
                                HourlyWage = hourlyWage
                            };

                            // add to list
                            datalist.Add(item);
                        
                        
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred while reading the CSV file: {ex.Message}");
            }

        }





        // Ignore this code
        private void LBLStatus_Click(object sender, EventArgs e)
        {

        }

        private void BTNVisualise_Click(object sender, EventArgs e)
        {
            Visualiser CHART = new Visualiser(datalist);
            CHART.Show();
            this.Enabled = false;
        }
    }
}

这是我使用数据并尝试创建图表的另一个页面,使用组合框作为用户按年份过滤信息的方式。

using System.Data;
using System.Windows.Forms.DataVisualization.Charting;

namespace AS2_U17_5th
{
    public partial class Visualiser : Form
    {
        private List<DataItems> datalist;
        public Visualiser(List<DataItems> datalist)
        {
            InitializeComponent();
            this.datalist = datalist;

            // Puts the year in the combobox if anything breaks this should be n1
            CBType.DataSource = datalist.Select(item => item.Year).Distinct().ToList();

            // Setting the primary data type to take from the combobox
            //CBType.SelectedIndex = 0;

            // Creates the chart 
            LoadChartMethod();
        }


        public void LoadChartMethod()
        {
            CHRTVisualisation.Series.Clear();   
            CHRTVisualisation.Series.Add("HourlyWage");

            //Get the seelected year from the Combobox
            int selectedYear = (int)CBType.SelectedItem;

            // Filter the datalist based on the selected year
            List<DataItems> filteredData = datalist.Where(item => item.Year == selectedYear).ToList();

            foreach (var item in filteredData)
            {
                // Add a data point to the chart
                CHRTVisualisation.Series["HourlyWage"].Points.AddXY(item.Ethnicity, item.HourlyWage);
            }


            // Set the labels and the title for the chart
            CHRTVisualisation.ChartAreas[0].AxisX.Interval = 1;
            CHRTVisualisation.Titles.Clear();
            CHRTVisualisation.Titles.Add($"Hourly Wages by Ethnicity - Year {selectedYear}");
            CHRTVisualisation.ChartAreas[0].AxisX.Title = "Ethnicity";
            CHRTVisualisation.ChartAreas[0].AxisY.Title = "Hourly Wage";


        }

        private void CBType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadChartMethod();

        }
    }
}

enter image description here

c# forms winforms charts streamreader
1个回答
0
投票

我使用的 Windows 窗体图表版本有问题,我切换到旧版本,它立即工作。

© www.soinside.com 2019 - 2024. All rights reserved.