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

寵の児 提交于 2019-12-09 00:43:06

问题


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.


回答1:


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.




回答2:


From the docs

In virtual mode, the Items collection is disabled. Attempting to access it results in an InvalidOperationException. The same is true of the CheckedItems collection and the SelectedItems collection. If you want to retrieve the selected or checked items, use the SelectedIndices and CheckedIndices collections instead.




回答3:


I you store all items in list and use this list to give item in RetrieveVirtualItem you can find selected items like following

Dim lstData As List(Of ListViewItem) = New List(Of ListViewItem)
Dim lstSelectedItems As List(Of ListViewItem) = lstData.FindAll(Function(lstItem As ListViewItem) lstItem.Selected = True)
Me.Text = lstItems.Count.ToString()



回答4:


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.



来源:https://stackoverflow.com/questions/3894222/cannot-access-the-selected-items-collection-when-the-listview-is-in-virtual-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!