循环遍历c#中的列表

时间:2015-06-24 15:55:35

标签: c# list loops

我在c#中编写了一些代码行来遍历列表,但是我只在文本框中打印了最后一个。我写的代码:

//For instantiation
Account account = new Account(0,"","", 0); 

//A list for class Account
List<Account> listAccount = new List<Account>();

//Button for adding new Customer
    private void button1_Click(object sender, EventArgs e)
    {
        account.CustomerID = int.Parse(customerIdTxt.Text);
        account.CustomerFullName = customerNameTxt.Text;
        account.CustomerAddress = customerAddrTxt.Text;
        listAccount.Add(account);

    }

    //For printing the Customer's detailes in textbox
    private void button6_Click(object sender, EventArgs e)
    {
        string showCustDetailes = "";
        for(int i=0;i<listAccount.Count;i++)
        {
            showCustDetailes+=
                "Customer ID        : " + listAccount[i].CustomerID + Environment.NewLine +
                "Customer Name      : " + listAccount[i].CustomerFullName + Environment.NewLine +
                "Customer Address   : " + listAccount[i].CustomerAddress + Environment.NewLine +
            "---------------------------------------------------" + Environment.NewLine;
        }
        viewDetailesTxt.Text = showCustDetailes;
    }

任何人都可以帮助我如何打印整个客户列表

1 个答案:

答案 0 :(得分:7)

循环遍历列表的代码没有任何问题(除了不使用foreach())。如果您真的只看到一个帐户,则问题在于显示:使文本框更大或给它滚动条。

此外,您每次都在编辑account的同一个实例,因此您在列表中填写了对同一帐户的多个引用。您必须使用new Account为每个“按钮1”单击实例化一个新的:

private void button1_Click(object sender, EventArgs e)
{
    Account account = new Account(0,"","", 0); 
    // ...
    listAccount.Add(account);
}