循环遍历c#中的列表

use*_*731 0 c# loops list

我在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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Cod*_*ter 7

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

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

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