2013-04-03 21 views
-2

所以,我试图首次实现一个列表。我最终将在三层设计中使用它,其中列表包含来自数据库查询的所有结果。我似乎无法让小项目工作。在C#中实现列表集合的难度

namespace listTest 

class Account 
{ 
    public string fName {get; set;} 
    public string lName {get; set;} 

    public Account() 
    { 
    } 

    public Account(string last, string first) 
    { 
     this.fName = first; 
     this.lName = last; 
    } 

    public void LoadAccounts() 
    { 
     List<Account> Accounts = new List<Account>(); 
     Accounts.Add(new Account("firstName", "lastName")); 
    } 
} 

所以,这是我的帐户类。我不得不在前言中说我不知道​​我是否正确实施了这一点。

private void getListBtn_Click(object sender, EventArgs e) 
{ 
    Account newAccount = new Account(); 
    List<Account> Accounts = new List<Account>(); 
} 

这里是我点击按钮加载列表。这里的想法是访问fName和lName值并更改我的表单上的两个标签。我现在所有的东西都是编译的方式,但是我的表示层上的fName和lName都是空值。我做这一切都错了吗?我觉得域层是列表的最佳位置。任何指导表示赞赏。

+2

哪里代码加载来自数据库的数据?当你创建一个新的'List'时,除非你添加东西(或者从现有的'List'中复制它),否则它将是空的。您发布的所有代码都在创建一个新的类型帐户列表。 – Tim 2013-04-03 18:46:10

+0

后来到了,现在我只是试图将字符串“firstName”和“lastName”放入我的表单类中。 – user1729696 2013-04-03 18:49:43

回答

2

你需要建立一个从数据库返回List<Account>这样

public List<Account> LoadAccounts() 
{ 
    List<Account> AccountsList = new List<Account>(); 

    // Get Accounts records from Database and add them into AccountsList as per your logic like this 

    AccountsList.Add(myaccount); 

    return AccountsList 
} 

的方法,那么你可以使用它你的表现层这样

private void getListBtn_Click(object sender, EventArgs e) 
{ 
    List<Account> Accounts = LoadAccounts(); 

    // now you can access first name and last name of each records like this 

    foreach(Account account in Accounts) 
    { 
    string firstName=account.fName ; 
    string lastName=account.lName ; 
    } 
} 
+0

我无法使用列表 Accounts = LoadAccounts();而无需实例化Account对象。我搞砸了一些代码,但我仍然有空值。 – user1729696 2013-04-03 19:05:57

+0

没有帐户anAccount =新帐户()我看不到帐户类中的方法。我认为这可能会产生我的空值。 – user1729696 2013-04-03 19:06:36

+0

你为什么在foreach循环中使用'anAccount.fName'。它应该像我在我的例子中描述的那样简单'account.fName'。帐户是我在foreach循环中使用的变量 – Sachin 2013-04-03 19:09:58