我遇到从文本文件(记事本文本文件)加载数据并将其显示在列表框中的问题。以下是我的代码,不确定它为什么不加载数据
private void loadData() {
try {
using (StreamReader reader = new StreamReader("visits.txt")) //Reads in file
{
string line;
while ((line = reader.ReadLine()) != null) {
string[] data = line.Split(','); //Splits the lines up when there is a ,
lstDeliveries.Items.Add(data[0] + ", " + data[1] + ", " + data[2]);
lstPickups.Items.Add(data[3] + ", " + data[4]);
}
}
}
catch (FileNotFoundException) {
MessageBox.Show("The file was not found!!"); //Provides error if file not found
Environment.Exit(0); //Closes application
}
}
答案 0 :(得分:2)
您没有提供任何类型的问题。我假设你文件中的某些行有意想不到的格式。添加条件以验证数据数组是否至少包含5个项目:
string[] data = line.Split(',');
if (data.Length >= 5)
{
lstDeliveries.Items.Add(String.Format("{0}, {1}, {2}", data[0], data[1], data[2]);
lstPickups.Items.Add(String.Format("{0}, {1}", data[3], data[4]);
}
同样String.Format
是格式化字符串的更好选择。