views:

255

answers:

1

I need to retrieve a set of data from a database, then populate a ListView with the data. I understand multithreaded form controls and the proper techniques for updating controls from worker threads. Here's the dilemma:

I may have several thousand entries in the ListView... rather than Invoking the form thread to update them one at a time, I'd like to build a collection of ListViewItem objects and use ListView.Items.AddRange(ListViewItemCollection).

However, the MSDN documentation advises not to create your own ListViewItemCollection (and indeed, trying to create my own ListViewItemCollection generates a null reference error because there's no parent set). Instead, MS recommends that you only work with a ListViewItemCollection by getting it via the ListView.Items property.

Which, of course, is circular reasoning and can't be done from a worker thread without generating an error: "Cross-thread operation not valid: Control 'ListView' accessed from a thread other than the thread it was created on."

I could use the overloaded AddRange(ListViewItem[]), but arrays are rather clunky in this day and age.

Anyone have a suggestion how to add several thousand items to a ListView from a worker thread?

+1  A: 

I think you already have your answer - AddRange(ListViewItem[]). If you find arrays distasteful, you can use a List and then do a toArray() right when you call AddRange.

Michael Donohue
Didn't think to do a List first, that's a good idea.I'll be curious to see which performs better, a generic List that is converted to an array or working with the array directly. If I work with the array directly I still have to call Resize() when I'm done adding items (I don't know up front how many items I will have) so both approaches end up copying all the elements to an array at the end... the List may even be faster.It surprises me that there isn't a better way to work with a ListViewItemCollection.
James B
Building List<ListViewItem> and copying it to ListViewItem[] runs about 500 milliseconds, vs. 600 milliseconds to work directly with a ListViewItem[]. See why I don't like arrays? : )My guess is because I don't know the size of the array up front, I'm losing time allocating space for the array that I don't need.
James B