我正在使用listview,并尝试使用文件填充。 我需要在表格开始后立即读入文件。
private void mainForm_Load(object sender, EventArgs e)
{
//get file read in
if (File.Exists("../../MealDeliveries.txt"))
{
StreamReader sr = new StreamReader("../../MealDeliveries.txt");
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}
}
private void displayDeliveries()
{
lstDeliveryDetails.Items.Clear();
foreach (Delivery d in mainForm.myDeliveries)
{
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
listview没有显示任何内容,尽管文件肯定在那里!
答案 0 :(得分:1)
是的,它应该假定文件位于您认为的位置。你肯定文件存在吗?
试试这个。它至少会确认是否找到了该文件。
private void mainForm_Load(object sender, EventArgs e)
{
string fileName = @"..\..\MealDeliveries.txt";
if (!File.Exists(fileName))
{
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader(fileName))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
while (strDeliveryName != null)
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
需要注意的另一件事是将字符串作为字符串读取以传递给业务对象(交付)。您可能会发现使用XmlSerializer提供的某种序列化格式或Marcos Meli's FileHelpers库支持的某种文件格式会更好。无论哪种方式,都需要比读取字符串更强大的东西。
答案 1 :(得分:0)
也许它会起作用但你还需要用IDisposable
包裹using
。像这样:
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt"))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}