$BlogRSDURL$>
This blog will describe some of the learning experiences that I have with .NET, some personal projects that I'm working on, and whatever other topics tickle my fancy.
My Blog LinksSite Links
Currently ReadingBlogroll
Archives
Tools |
Friday, March 26, 2004ArrayList with Events (Part 1)
I recently was involved in a thread on GotDotNet about responding to ArrayList changes in the UI. DalanGalma wanted to populate a ListView with data from an ArrayList and keep it in synch with the associated data objects. Having an ArrayList that fired events (this could also be done for other collections as well) when things changed could be generally useful, not just for keeping the ListView up to date. So, I decided to create one (after a few searches for something like that on the web).
So, first thing to do was figure out what events to send. I decided on having several:
The interesting thing about ArrayItemsChanged is that data objects need to fire it, and it doesn't get fired when you set an item into an array position. myArray[index] = newItem;Instead, I decided to fire an ArrayItemsRemoved followed by ArrayItemsAdded (rather than ArrayItemsChanged) because the item itself isn't actually changing, but the item that was at that position in the ArrayList is being replaced by the new item. It's debatable as to which is better, but if you feel that ArrayItemsChanged should be fired instead, feel free to update the code in the sample to your requirements. Here's some of the code for the EventedArrayList class:
You'll notice that I didn't override AddRange or Remove because they call through to other methods (InsertRange and RemoveAt respectively) that already fire events, so you would get multiple events fired in those cases. Counter-intuitively, you do need fire an event for Clear because it doesn't call into RemoveRange as I thought it might... gotta love consistency. :) Note: This class does not contain an overloaded constructor that takes an ICollection similar to the one ArrayList has. No events are fired during the class's creation because no one could be listening for them yet anyway, so you would not get notification that these items were added in the constructor. Therefore, I decided to leave that method out.
Finally, the ArrayListEventArgs class is used by all of the events. This class simply keeps a list of items that have been manipulated by an EventedArrayList operation. This is passed into the event handlers, so that they can use that information to respond accordingly. In my next blog entry, I'll discuss the data object that fires change events... You can download the full sample code from GotDotNet or look at it online and report bugs at the workspace.
Comments:
Post a Comment
|