2013-10-09 37 views
0

在大家的幫助下,我想出了這個代碼,它從.txt文件加載數據庫,並使用這些值填充列表。我在使用列表獲取值時遇到了一些麻煩。繼承人在我的Program.cs從C#中的列表中獲取價值

static class Program 
{ 

    var customers = new List<Customer>(); 

    static void loadData() //Load data from Database 
    { 
     string[] stringArray = File.ReadAllLines("Name.txt"); 
     int lines = stringArray.Length; 
     if (!((lines % 25) == 0)) 
     { 
      MessageBox.Show("Corrupt Database!!! Number of lines not multiple of 25!"); 
      Environment.Exit(0); 
     } 
     for(int i = 0;i<(lines/25);i++){ 
      customers.Add(new Customer 
      { 
       ID=stringArray[(i*25)], 
       Name = stringArray[(i * 25) + 1], 
       Address = stringArray[(i * 25) + 2], 
       Phone = stringArray[(i * 25) + 3], 
       Cell = stringArray[(i * 25) + 4], 
       Email = stringArray[(i * 25) + 5], 
       //Pretend there's more stuff here, I'd rather not show it all 
       EstimatedCompletionDate = stringArray[(i * 25) + 23], 
       EstimatedCompletionTime = stringArray[(i * 25) + 24]  
      }); 
     } 
    } 

    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     loadData(); 
     Application.Run(new Form1()); 
    } 
} 

的代碼,並從Class1.cs的代碼 - Customer類

public class Customer 
{ 
    public string ID { get; set; } 
    public string Name { get; set; } 
    public string Address { get; set; } 
    public string Phone { get; set; } 
    public string Cell { get; set; } 
    public string Email { get; set; } 
    //Pretend there's more stuff here 
    public string EstimatedCompletionDate { get; set; } 
    public string EstimatedCompletionTime { get; set; } 
} 

但是,如果我嘗試從customers[1].ID編輯獲得的價值(從form2.cs) ,我得到「在當前情況下客戶不存在」。我如何宣佈客戶可以在任何地方訪問?

謝謝! :)

回答

2

您可以將customers對象傳遞給Form2或創建一個靜態列表。無論哪種方式,它需要是靜態的,因爲loadData是靜態的。

爲了讓靜態的,在你的Program.cs中,你可以這樣做:

public static List<Customer> Customers { get; set; } 

LoadData第一行只是做:

Form1.Customers = new List<Customer>(); 

然後任何時候,你需要訪問它只是叫做Form1.Customers(例如:Form1.Customers[1].ID

+0

作爲C#中的noob,這個答案很容易理解,我認爲它正是我想要的。我現在距離C#掌握更近了一步! ;) – Nathan

1

您的customers變量在您的Form2類中根本不可見。您需要將customers傳遞給Form2類的實例(通過自定義構造函數,方法參數或通過設置Form2類上實現的公共屬性/字段來注入它)。

你需要的東西是這樣的:

public partial class Form2 : Form 
{ 
    // add this... 
    public List<Customer> Customers 
    { 
     get; 
     set; 
    } 

然後,如果你在你的Program創建Form2,你做的是一樣的東西:

Form2 f2 = new Form2(); // supposing you have this already, whatever you named it 
f2.Customers = customers; // customers being your variable 

如果您建立Form2從在Form1之內,那麼你必須先通過customersForm1,例如。因爲Adam Plocher向您展示了(如果您將其設爲靜態),然後再向Form2顯示,但原理保持不變。

在一個側面說明,這不是一個很好的編程習慣,但這超出了你的問題的範圍。

+0

我該如何讓它在整個程序中可見和可用? – Nathan

+0

糟糕的編程習慣?有人在另一個問題上告訴我,這是最好的方式!我看看這是否有效。這些變量是否仍然可以從我傳給它的任何類中編輯?因爲客戶(i)在運行時需要隨時可編輯。 – Nathan

0

loadData()static,所以它看不到非靜態的實例變量。將var customers更改爲static var customers