读取csv文件并输出到列表框&可以编辑的列表

时间:2018-04-10 22:37:55

标签: c# list csv class inventory

我正在尝试制作一个Windows窗体应用程序,允许用户加载选定的csv文件(任何具有相同格式的csv文件)并能够编辑列表。必须使用OpenFileDialog和output into a list box in a formatted way打开csv文件。用户加载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;
    }
}

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

2 个答案:

答案 0 :(得分:0)

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

取而代之的是DataGridView

  • 首先查看如何'将cvs读取到DataTable'并执行此操作。

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

  • 最后如何'序列化DataTable'

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

您的类只有简单的数据类型,只需简单地附加[Serializable]属性即可进行序列化。这也适用于List<Inventory>,但有更好的方法。

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

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

答案 1 :(得分:-1)

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