2012-11-26 128 views
-1

我遇到了從文本文件(記事本txt文件)中加載數據並將其顯示在列表框中的問題。以下是我的代碼,不知道爲什麼它不加載數據將文本文件中的數據添加到列表框

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 
     } 
    }   
+2

而問題是... –

+0

您至少可以提供您的問題的描述,即異常消息 – horgh

+0

我沒有任何異常消息 – littledevils326

回答

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是一個更好的選擇格式字符串。

+0

爲什麼length> = 5? – littledevils326

+0

@ littledevils326,因爲你試圖訪問數組'data [4]' –

+0

中的第五項,謝謝它的工作。也許我是愚蠢的,但我仍然不明白爲什麼你需要如果(data.Length> = 5) – littledevils326

相關問題