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.
I've done it by the following code, but it has an exception when more than one item are selected:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
List<ListViewItem> ListViewItems = new List<ListViewItem>();
foreach (int index in listView1.SelectedIndices)
{
ListViewItem SelectedListViewItem = listView1.Items[index]; // exception
ListViewItems.RemoveAt(index);
}
…
void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = ListViewItems[e.ItemIndex];
}
Whenever you remove item(s) from a collection, always iterate from the largest index to the smallest index, like this:
for (int index = listView1.SelectedIndices.Count - 1; i >= 0; i--)
{
…
}
This is because every time you remove an item in a collection, the index will change if you do not iterate from the largest to the smallest index.