我基本上是在尝试将 .txt 文件中的项目添加到listbox
. 问题是加载.txt文件的方法是在一个单独的类中,所以我到了不知道该怎么做的地步。任何帮助将不胜感激。这是具有文件加载方法的类:
public class BunchOfDeliverables
{
private List<Person> myPersons;
private List<Deliverable> myDeliverables;
public BunchOfDeliverables()
{
this.myPersons = new List<Person>();
this.myDeliverables = new List<Deliverable>();
}
public List<Person> Persons { get { return this.myPersons; } }
public List<Deliverable> Deliverables { get { return this.myDeliverables; } }
public void LoadPersonsFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String name, street, housenr, postalcode, city;
name = sr.ReadLine();
while (name != null)
{
street = sr.ReadLine();
housenr = sr.ReadLine();
postalcode = sr.ReadLine();
city = sr.ReadLine();
this.myPersons.Add(new Person(name, street, Convert.ToInt32(housenr), postalcode, city));
name = sr.ReadLine();
name = sr.ReadLine(); //and again read a line, because of the delimiter (line with the stars)
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void LoadDeliverablesFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String s;
s = sr.ReadLine();
while (s != null)
{
String[] items = s.Split();
this.myDeliverables.Add(new Deliverable(Convert.ToInt32(items[0]), Convert.ToInt32(items[1]), this.myPersons[Convert.ToInt32(items[2])]));
s = sr.ReadLine();
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void AddPerson(Person p)
{
this.myPersons.Add(p);
}
public Deliverable FindDeliverable(int id)
{
foreach (Deliverable d in this.myDeliverables)
{
if (d.ID == id)
{
return d;
}
}
return null;
}
public void AddDeliverable(Deliverable d)
{
if (FindDeliverable(d.ID) == null)
{
myDeliverables.Add(d);
}
else
{
throw new Exception("Be aware: nothing is added!!!");
}
}
然后这里是表单类(大部分是空的):
public partial class Form1 : Form
{
BunchOfDeliverables d;
public Form1()
{
InitializeComponent();
d = new BunchOfDeliverables();
}
private void AddLoadedFilesToListbox_Click(object sender, EventArgs e)
{
}
Edit :
我尝试了以下方法,但它再次不起作用:
公共部分类 Form1 : Form { BunchOfDeliverables d; 公共 Form1() { InitializeComponent(); d = new BunchOfDeliverables(); d.LoadDeliverablesFromFile("..data/deliverables.txt"); }
private void button1_Click(object sender, EventArgs e)
{
foreach (Deliverable deliv in d.Deliverables)
{
listBox1.Items.Add(deliv);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}