Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top