How to keep an updated listbox of objects?
I am having trouble keeping a ListBox updated with child objects.
I'm using two List
s, total and current, and a Timer; every 1000ms the current set of child objects is queried, and appende开发者_如何学编程d to my total list. My current list is then instantiated with only the current items (read not the total).
I'm then comparing the total list and the current list. Any objects in the total list, not found in the current list, are removed, and subsequently each object from the total list is then added to the ListBox.
private List<IAgStkObject> _liveListOfEntities;
private List<IAgStkObject> _totalListOfEntities = new List<IAgStkObject>();
private void UpdateEntityList() {
IAgStkObjectElementCollection stkScenarioEntities;
if (_stkObjectRoot.HasChildren) {
_liveListOfEntities = new List<IAgStkObject>();
foreach (AgESTKObjectType typeOfElement
in Enum.GetValues(typeof(AgESTKObjectType))) {
stkScenarioEntities =
_stkObjectRoot.CurrentScenario.Children.GetElements(typeOfElement);
foreach (IAgStkObject entity in stkScenarioEntities) {
_liveListOfEntities.Add(entity);
if (!_totalListOfEntities.Contains(entity)) {
_totalListOfEntities.Add(entity);
}
}
}
foreach (IAgStkObject entity in _totalListOfEntities) {
if (!_liveListOfEntities.Contains(entity)) {
// remove
_totalListOfEntities.Remove(entity);
}
else if (!lsbEntities.Items.Contains(entity.InstanceName)) {
lsbEntities.Items.Add(entity.InstanceName);
}
}
}
I keep getting an exception when any object is removed: Collection was modified; enumeration operation may not execute.
You should not remove items from a collection in the midst of iterating it. Instead, you should create a temporary List<>
to store references to the items that you determine must be removed, and then remove them in code outside of the code that is using the iterator.
@Andrew Barber has the reason why you are getting collection modified exceptions.
As an aside, seems like you would want to isolate your GUI from the implementation of the poll to get the most recent state of the objects.
Why not create a custom collection that implements IBindingList
(perhaps by deriving from BindingList) and then bind that to the GUI.
I found a more elegant solution here.
精彩评论