Question

How to enumerate a ListView when it is in virtual mode ?

I'm using OfType<>() method to enumerate the list view items. But its throwing an exception like, the list view can not be enumerated when it is in virtual mode.

Here is my code

List<String> lst= myListView.Items.OfType<ListViewItem>().Select(X=>X.Text).ToList(); 

So how do i get the item from the ListView when it is in Virtual mode?

Please post me a way to use .OfType<>

Thanks in advance

Was it helpful?

Solution

When it's in virtual mode you can't get the items out of the list view because the items aren't in the list view. That's the whole point of virtual mode.

Instead, you hold the items and the list view asks for the information it needs to display the items. If you are operating a list view successfully in virtual mode then you almost certainly already have the items in a list somewhere.

Quoting from the documentation:

Setting the VirtualMode property to true puts the ListView into virtual mode. In Virtual mode, the normal Items collection is unused. Instead, ListViewItem objects are created dynamically as the ListView requires them.

Virtual mode can be useful under many circumstances. If a ListView object must be populated from a very large collection already in memory, creating a ListViewItem object for each entry can be wasteful. In virtual mode, only the items required are created. In other cases, the values of the ListViewItem objects may need to be recalculated frequently, and doing this for the whole collection would produce unacceptable performance. In virtual mode, only the required items are calculated.

OTHER TIPS

The ListViewItemCollection.GetEnumerator() method throws an exception if it is called when the list is in virtual mode. This means it will be impossible for you to access them via any LINQ method, including OfType().

However, you can just do a simple iteration of the list:

List<string> lst = new List<string>();
for (int i = 0; i < listView1.VirtualListSize; i++) {
   lst.Add(listView1.Items[i].Text);

However (again), if the list is virtual, it probably has a large number of items, so this could take a while :)

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