Cannot access the selected items collection when the ListView is in virtual mode?

Mohammad Dayyan picture Mohammad Dayyan · Oct 8, 2010 · Viewed 9.5k times · Source

I have a ListView in Virtual Mode. I wanna to access SelectedItems property.
But when I use ListView1.SelectedItems , I receive the following Exception :

Cannot access the selected items collection when the ListView is in virtual mode

How can I access to ListView1.SelectedItems in VirtualMode.

Answer

Mariusz picture Mariusz · Aug 28, 2011

It is quite old post but maybe someone else will benefit.

Simply use ListView.SelectedIndexCollection col = listView.SelectedIndices; Then you can access an item:

forearch(var item in col)
{
   string txt = listView.Items[item].Text;
}

..but you won't be able to iterate through ListView.Items using foreach because there is no iterator available in this mode. Using indexer is just flying fine :-)

When trying to use foreach you get an exception:

When the ListView is in virtual mode, you cannot enumerate through the ListView items collection using an enumerator or call GetEnumerator. Use the ListView items indexer instead and access an item by index value.