【发布时间】: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