MrME
MrME

Reputation: 337

How to add items from an XML file to an already filled List<> thats bound to an ListBox

Heey Stackoverflowers

I am currently busy with a listbox with a List<> binded to it. I fill this List<> by a api call to our web server. Now when i reach the bottom of the list i display an "Load More" button when i press the button i start up another call to our api but then for 20 new items. Now is my Question how can i Add those 20 new items to my List<> without deleting the older 20.

This is how i fill the List<> at the moment

eventList = (from item in events.Descendants("item")
             select new Events
             {
             EventId = Convert.ToInt16(item.Element("eventid").Value),
             EventName = item.Element("eventname").Value,
             EventType = Convert.ToInt16(item.Element("type").Value)
             }).ToList();

Dispatcher.BeginInvoke(new Action(
() =>
     lbVanAlles.ItemsSource = eventList
));

But if i do this with my 20 new items they overwrite my old ones. So anybody got any clue? Probably something with eventList.Add but then i get errors that i cant assign it to a "method group"

Upvotes: 1

Views: 235

Answers (1)

Praetorian
Praetorian

Reputation: 109219

Instead of overwriting eventList every time with the result of the Linq query, use the List.AddRange method to append items to the existing list.

var temp = from item in events.Descendants("item")
             select new Events
             {
             EventId = Convert.ToInt16(item.Element("eventid").Value),
             EventName = item.Element("eventname").Value,
             EventType = Convert.ToInt16(item.Element("type").Value)
             };
eventList.AddRange( temp );

Also, instead of reassigning lbVanAlles.ItemsSource each time you can switch over to using an ObservableCollection instead of a List. This will notify the ListBox when items are added and it will update automatically.

Upvotes: 4

Related Questions