Search code examples
c#arrayslistforeachobservablecollection

ObseservableCollection not getting populated correctly using foreach (C#)


I use an array and foreach to fill up a list. But the WPF GUI only shows me the last item from the array and not all of them. The binding is correct, there must be a logical error in my code:

public ObservableCollection<Client> Clients { get; set; }

string[] clients = { 
            "XYZ.company.server",
            "ABC.company.server"
}

foreach (string item in clients)
{
    Client client = new Client(item);
    Clients = new ObservableCollection<Client>();
    Clients.Add(client);
}

this.DataContext = this;

The Gui only shows "ABC.company.server" on the ListView.


Solution

  • You need to declare collection before loop. So while looping your collection will add items from foreach loop.

    Clients = new ObservableCollection<Client>();
    foreach (string item in clients)
    {
        Client client = new Client(item);
    
        Clients.Add(client);
    
    }
    

    Otherwise, your collection will be recreated each time in loop and all previous iterated items will not be added into newly created collection.