2012-12-16 144 views
1

我希望在單擊「列出所有客戶」按鈕時,代碼應該讀取Customer.csv文件並在名爲「列出所有客戶」的表單上顯示信息。閱讀文件和顯示內容

我該怎麼做?

public static void ReadFile() 
{ 
    StreamReader sr = File.OpenText("Customer.csv"); 
} 

public static void LoadCustomers() 
{ 
    try 
    { 
     if (File.Exists("Customer.csv")) 
     { 
      string temp = null; 
      int count = 0; 

      using (StreamReader sr = File.OpenText(@"Customer.csv")) 
      { 
       while ((temp = sr.ReadLine()) != null) 
       { 
        temp = temp.Trim(); 
        string[] lineHolder = temp.Split(','); 
        Customer tempCust = new Customer(); 
        tempCust.customerName = lineHolder[0]; 
        tempCust.customerAddress = lineHolder[1]; 
        tempCust.customerZip = Convert.ToInt32(lineHolder[2]); 
        myCustArray[count] = tempCust; 
        count++; 
       }//end for loop 
      } 
     } 
     else 
     { 
      File.Create("Customer.csv"); 
     } 
    } 
    catch (Exception e) 
    { 
     System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message); 
    } 
} 

回答

0

我不知道你想顯示在這個數據是什麼樣的控制但你的方法可能只是返回的Customer列表,那麼你可以添加到ListBoxListViewDataGrid

public static IEnumerable<Customer> LoadCustomers(string filename) 
{ 
    if (File.Exists(filename)) 
    { 
     foreach (var line in File.ReadAllLines(filename).Where(l => l.Contains(','))) 
     { 
      var splitLine = line.Split(','); 
      if (splitLine.Count() >= 3) 
      { 
       yield return new Customer 
       { 
        customerName = splitLine[0].Trim(), 
        customerAddress = splitLine[1].Trim(), 
        customerZip = Convert.ToInt32(splitLine[2].Trim()) 
       }; 
      } 
     } 
    } 
} 

列表框

listBox1.DisplayMember = "customerName"; 
listBox1.Items.AddRange(LoadCustomers(@"G:\Customers.csv").ToArray()); 
0

首先,利用列表的對象:

public static void ReadFile() 
{ 
    StreamReader sr = File.OpenText("Customer.csv"); 
} 

public static void LoadCustomers() 
{ 
    try 
    { 
     if (File.Exists("Customer.csv")) 
     { 
      string temp = null; 
      var retList = new List<Customer>(); 
      using (StreamReader sr = File.OpenText(@"Customer.csv")) 
      { 
       while ((temp = sr.ReadLine()) != null) 
       { 
        temp = temp.Trim(); 
        string[] lineHolder = temp.Split(','); 
        retlist.add(new Customer(){ 
         customerName = linerHolder[0], 
         customerAddress = lineHolder[1], 
         customerZip = Convert.ToInt32(lineHolder[2]) 
        }); 
       }//end for loop 
      } 
     } 
     else 
     { 
      File.Create("Customer.csv"); 
     } 
    } 
    catch (Exception e) 
    { 
     System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message); 
    } 
} 

只是將它包裝在一個類中,如果從控制器調用並填充結果。根據您更新此數據的頻率,您可能會考慮緩存它,因此您不必每X秒爲每個用戶運行此過程。