【问题标题】:Read csv file and output into a list box & list that can be edited读取csv文件并输出到可以编辑的列表框和列表中
【发布时间】:2018-04-10 22:37:55
【问题描述】:

我正在尝试制作一个允许用户加载所选 csv 文件(具有相同格式的任何 csv 文件)并能够编辑列表的 Windows 窗体应用程序。 csv 文件必须使用 OpenFileDialog 和output into a list box in a formatted way 打开。用户加载 csv 文件后,需要添加更改列表数据的选项。

表格代码:

    public partial class inventoryForm : Form
    {
    OpenFileDialog ipFile = new OpenFileDialog();
    public inventoryForm()
    {
        InitializeComponent();
    }
    private void loadInvDataButton_Click(object sender, EventArgs e)
    {
        inventoryListBox.Items.Clear(); //clear listbox items
        if (ipFile.ShowDialog() == DialogResult.OK) //show dialog box
        {
            Inventory inventory = new Inventory();
            var inventories = inventory.Load(ipFile.FileName);
            //sets the datasource of the list box to the collection of inventory
            //by default it calls the ToString() method which which overrode
            //to provide columar output
            inventoryListBox.DataSource = inventories;
        }
    }

类代码:

public class Inventory
{
    public string Id { get; set; }
    public string ItemName { get; set; }
    public int StartingQty { get; set; }
    public int QtyMinRestck { get; set; }
    public int QtySold { get; set; }
    public int QtyRStcked { get; set; }
    public decimal UnitPrice { get; set; }

    public Inventory()
    {

    }

    //this overrides the default .ToString() method to provide
    //columnar output and formats the UnitPrice to currrency
    //this requires the following: using System.Globalization;
    public override string ToString()
    {
        return String.Format("{0}{1}{2}{3}{4}{5}{6}"
            , Id.PadRight(20, ' ')
            , ItemName.PadRight(20, ' ')
            , StartingQty.ToString().PadLeft(20, ' ')
            , QtyMinRestck.ToString().PadLeft(20, ' ')
            , QtySold.ToString().PadLeft(20, ' ')
            , QtyRStcked.ToString().PadLeft(20, ' ')
            , UnitPrice.ToString("C", CultureInfo.CurrentCulture).PadLeft(20, ' '));
    }

    //this loads a collection of inventory objects from a file
    //it would ignore any lines with errors
    public IEnumerable<Inventory> Load(string InventoryFileName)
    {
        var inventories = new List<Inventory>();
        using (var sr = new StreamReader(InventoryFileName))
        {
            sr.ReadLine(); //skip the first line
            while (!sr.EndOfStream)
            {
                try
                {
                    var fields = sr.ReadLine().Split(',');

                    inventories.Add(new Inventory
                    {
                        Id = fields[0]
                        ,
                        ItemName = fields[1]
                        ,
                        StartingQty = Int32.Parse(fields[2])
                        ,
                        QtyMinRestck = Int32.Parse(fields[3])
                        ,
                        QtySold = Int32.Parse(fields[4])
                        ,
                        QtyRStcked = Int32.Parse(fields[5])
                        ,
                        UnitPrice = Decimal.Parse(fields[6])
                    });
                }
                catch
                {
                    //handle error here
                }
            }
        }
        return inventories;
    }
}

有人告诉我,我拥有的这段代码需要序列化,因为它目前已反序列化。我不知道该怎么做。我相信即使添加了代码,我当前的代码也不允许用户进行编辑。

【问题讨论】:

    标签: c# list csv class inventory


    【解决方案1】:

    ListBox 可以显示您的课程,但不适合您的所有其他任务。

    改为使用DataGridView

    • 先看看如何'read cvs to DataTable',然后去做。

    • 接下来如何'将 DataTable 绑定到 DataGridView'

    • 最后如何'序列化一个DataTable'

    虽然ListBox 的显示可能没问题,但只要将其限制为固定字体,就无法对其进行编辑。

    您的类只有简单的数据类型,只需附加[Serializable] 属性即可使其可序列化。这也适用于List&lt;Inventory&gt;,但有更好的方法。

    DataTable 可序列化开箱即用,DGV 允许您默认编辑所有单元格..

    生成的代码将包含一种将 cvs 加载到 xml 的方法 (GetDataTableFromCsv) 和一两行用于保存和加载数据到 xml 的各行(序列化)。所有这些都可以在前一两个谷歌点击中找到。

    【讨论】:

      【解决方案2】:
      enter code here
                  head = reader.ReadLine(); 
      
                  while(!reader.EndOfStream)
                  {
                      string[] line = reader.ReadLine().Split(';'); 
      
                      Class rep;
      
                      if (line[2] == "2.0")
                          rep = new Class2(line);
                       else if (line[2] == "2.1")
                          rep = new Class21(line);
                      else
                          rep = new Class51(line); 
      
                      listReproduktoru.Add(rep); 
                  }
              }
              UpdateView();
      enter code here
      

      【讨论】:

      • 欢迎来到堆栈溢出。请注意,可以通过描述它如何解决问题来改进您的答案,并提供一些上下文。顺便说一句,我发现您的代码不完整(没有定义 Class、Class2、Class21、Class51)并且我不确定它是否解决了问题的问题。
      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多