Home > Back-end >  ForEach loop but using a generic list as a parameter
ForEach loop but using a generic list as a parameter

Time:04-30

Well I've made a display method and it's a list so what I'm trying to do with no success is getting it to display it but I'm not able to as it's running into the CS1503 error which I'm unable to figure out and I'm just after some guidance on the matter/solution.

I end up with the error occurring in Class B in the foreach loop at manageAccounts.DispalyBasicInfo(item);

I'm only still learning C#.

Class A:

public void DisplayBasicInfo(List<Account> lstAcc)
{
    foreach (var item in lstAcc)
    {
        Account objAccTemp = item;
        lblCustomerName.Text = objAccTemp.CustomerName;
        lblCustomerNo.Text = objAccTemp.AccountID.ToString();
        if (objAccTemp.AccountType != null)
        {
            lstAccounts.Items.Add(objAccTemp.AccountID   " "   objAccTemp.AccountType   " $"   objAccTemp.BankBalance);
        }
    }
}

Class B:

private void btnManageAccount_Click(object sender, EventArgs e)
{
    try
    {
        ManageAccounts manageAccounts = new ManageAccounts();
        string strTemp = lstCustomers.SelectedItem.ToString();
        foreach (var item in Controller.lstAccounts)
        {
            if (item.CustomerName == strTemp)
            {
                manageAccounts.DisplayBasicInfo(item);
            }
        }
        manageAccounts.Show();
        Close();
    }
    catch (Exception)
    {
        MessageBox.Show("Please select a customer or create one", "No Selection");
    }
}

CodePudding user response:

The DisplayBasicInfo() method expects an entire list:

public void DisplayBasicInfo(List<Account> lstAcc)

But when you call it, you don't have a list. You only have a single account:

manageAccounts.DisplayBasicInfo(item);

Additionally, if you did pass a whole list to method, only last item would show on the screen, since the loop overwrites the same items on every iteration.

Therefore you probably want this:

public void DisplayBasicInfo(Account account)
{
    lblCustomerName.Text = account.CustomerName;
    lblCustomerNo.Text = account.AccountID.ToString();
    if (account.AccountType != null)
    {
        lstAccounts.Items.Add($"{account.AccountID} {account.AccountType} {account.BankBalance:C2}";
    }
}

Last of all, I don't know who's teaching you to use prefixes like lst or obj, but that's no longer recommended. It made sense back in the old days, but now tooling has improved. Even Microsoft, where the practice was created, now specifically publishes style guidelines asking people not to use this notation.

  • Related