使用 BindingSource 将 CSV 加载到列表中
本文关键字:列表 加载 CSV BindingSource 使用 | 更新日期: 2024-11-07 20:16:53
我正在尝试使用BindingSource将包含"工作站"列表的csv文件加载到列表中。 这是我现在所拥有的。
OpenFileDialog of = new OpenFileDialog();
List<Workstation> invList = new List<Workstation>();
BindingSource bs = new BindingSource();
bs.DataSource = invList;
listBox1.DisplayMember = "display";
public class Workstation
{
public string name { get; set; }
public string serviceTag { get; set; }
public string display
{
get
{
return name + " | " + serviceTag;
}
}
public string type { get;set; }
public string os { get; set; }
public string make { get; set; }
public string model { get; set; }
public int hd { get; set; }
public int ram { get; set; }
public string location { get; set; }
public string ip { get; set; }
public string notes { get; set; }
}
private void resume()
{
try
{
filePath = of.FileName;
var loadedWorkstation = new Workstation();
string[] line = System.IO.File.ReadAllLines(filePath);
List<string> doc = new List<string>();
for(int x = 0;x < line.Length; x++)
{
doc = line[x].Split(',').ToList();
loadedWorkstation.name = doc[0];
loadedWorkstation.serviceTag = doc[1];
loadedWorkstation.make = doc[2];
loadedWorkstation.model = doc[3];
loadedWorkstation.ram = Convert.ToInt32(doc[4]);
loadedWorkstation.hd = Convert.ToInt32(doc[5]);
loadedWorkstation.os = doc[6];
loadedWorkstation.location = doc[7];
loadedWorkstation.type = doc[8];
loadedWorkstation.ip = doc[9];
loadedWorkstation.notes = doc[10];
invList.Insert(0, loadedWorkstation);
bs.ResetBindings(false);
listBox1.DataSource = bs;
}
}
}
我遇到的问题是csv文件看起来像这样:
Dave's PC,19NMX32,Dell,Optiplex 2010,0,0,,Office Desk,,10.10.77.138,
Blake's PC,20NMX12,Dell,Optiplex 3020,0,0,,Office Desk,,10.10.77.136,
John's PC,4NMX17,Dell,Optiplex 3020,0,0,,Office Desk,,10.10.77.131,
Jake's PC,12NMX32,Dell,Optiplex 3020,0,0,,Office Desk,,10.10.77.132,
当我加载它时,列表和列表框显示以下内容:
Dave's PC | 19NMX32
Dave's PC | 19NMX32
Dave's PC | 19NMX32
Dave's PC | 19NMX32
只需移动此行
var loadedWorkstation = new Workstation();
循环内部
for(int x = 0;x < line.Length; x++)
{
doc = line[x].Split(',').ToList();
var loadedWorkstation = new Workstation();
loadedWorkstation.name = doc[0];
....
当前代码始终使用 Workstation
类的同一实例。您可以为文件中的每个行重复添加相同的实例。
在循环中,您不会构建新实例,而是更改唯一创建的工作站实例的属性。这会导致在循环结束时,这个孤独的实例等于加载的最后一行,并且您的列表显示每个项目的相同引用。
如问题下的评论中所述,您可能也可以移动这些行
bs.ResetBindings(false);
listBox1.DataSource = bs;
环外